🚩传送门:牛客题目
题目
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = [“flower”,”flow”,”flight”] 输出:“fl”
示例 2:
输入:strs = [“dog”,”racecar”,”car”] 输出:“” 解释:输入不存在公共前缀。
解题思路1:横向扫描
用 表示字符串
的最长公共前缀。可以得到以下结论:
基于该结论,可以得到一种查找字符串数组中的最长公共前缀的简单方法。依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。![[NC]55. 最长公共前缀 - 图4](/uploads/projects/mylearn@leetcode/421816b0cc9359397f745f026a3c8689.png)
如果在尚未遍历完所有的字符串时,最长公共前缀已经是空串,则最长公共前缀一定是空串,因此不需要继续遍历剩下的字符串,直接返回空串即可。
复杂度分析
时间复杂度:,其中
是字符串数组中的字符串的平均长度,其中
是字符串的数量。
- 最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次。
空间复杂度:,使用的额外空间复杂度为常数。
官方代码
class Solution {public String longestCommonPrefix(String[] strs) {if (strs == null || strs.length == 0) {return "";}String prefix = strs[0];int count = strs.length;for (int i = 1; i < count; i++) {prefix = longestCommonPrefix(prefix, strs[i]);if (prefix.length() == 0) {break;}}return prefix;}// 获取两个字符串的共同前缀public String longestCommonPrefix(String str1, String str2) {int length = Math.min(str1.length(), str2.length());int index = 0;while (index < length && str1.charAt(index) == str2.charAt(index)) {index++;}return str1.substring(0, index);}}
解题思路2:纵向扫描
方法一是横向扫描,依次遍历每个字符串,更新最长公共前缀。另一种方法是纵向扫描。纵向扫描时,从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。
复杂度分析
时间复杂度:,其中
是字符串数组中的字符串的平均长度,其中
是字符串的数量。
- 最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次。
空间复杂度:,使用的额外空间复杂度为常数。
官方代码
class Solution {public String longestCommonPrefix(String[] strs) {if (strs == null || strs.length == 0) {return "";}int length = strs[0].length(); // 第一行的列数,因为答案不超过此列数int count = strs.length; // 总共的行数for (int i = 0; i < length; i++) {char c = strs[0].charAt(i); // 拿到第一行的每一列的元素for (int j = 1; j < count; j++) { // 逐个和此列的所有行比较if (i == strs[j].length() || strs[j].charAt(i) != c) { // 直至末尾或不等return strs[0].substring(0, i); // 返回答案}}}return strs[0];}}
