题目来源: 14. 最长公共前缀
题目描述:
- 描述: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
- 示例:
示例1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
思路
用表示字符串的最长公共前缀。
所以我们可以得到以下的一个结论:
基于得到的这个结论,我们可以得到一种查找字符串数组中的最长公共前缀的简单的方法:
依次去遍历字符串数组中的每一个字符串,对于每一个遍历到的字符串,更新最长公共前缀,当我们遍历完所有的字符串以后,就可以得到字符串数组中的最长公共前缀了。
如果是在尚未遍历完所有的字符串的时候,最长公共前缀已经是空串了,那么最长公共前缀一定就是空串,因此我们完全就不需要再继续遍历剩下的字符串了,直接返回空串就可以了。
具体实现
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);
}
}
复杂度分析:
-
时间复杂度:O(mn),其中m 是字符串数组中的字符串的平均长度,n 是字符串的数量。在最坏的情况下,字符串数组中的每一个字符串的每一个字符都会被比较一次。
-
空间复杂度:O(1),使用的额外空间复杂度为常数