https://leetcode-cn.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note: All given inputs are in lowercase letters a-z.
我的思路是纵向扫描,先取了字符串数组中长度最短的那个当作遍历模板,这样保证不会越界,然后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀;
上代码:
public String longestCommonPrefix(String[] strs) {
int smallestLength = -1;
String smallestValue = "";
List<String> leftStr = new ArrayList<>();
for(String str : strs){
if(smallestLength > str.length()){
//最小的不放入leftStr
leftStr.add(smallestValue);
smallestLength = str.length();
smallestValue = str;
} else{
if(smallestLength==-1){
smallestLength = str.length();
smallestValue = str;
}else{
leftStr.add(str);
}
}
}
for(int i = 0;i<smallestLength;i++){
Character compareNum = smallestValue.charAt(i);
for(String str : leftStr){
if(compareNum != str.charAt(i)){
return smallestValue.substring(0,i);
}
}
}
return smallestValue;
}
看了官方代码,发现自己先取最短的字符串是多余的,优化后代码:
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
//选取第一个字符串作为遍历模板
String template = strs[0];
int count = strs.length;
//外层遍历模板字符元素
for(int i = 0; i < template.length(); i++){
Character compareNum = template.charAt(i);
//内层遍历剩下的数组元素;
for(int j = 1; j < count; j++){
//当template比其余数组元素长时(template较短时完全不必担心),遍历时会出现越界,所以有两种情况直接返回值
//1、当外层循环i等于其余数组元素时 2、相同位置值不相等时
if(i == strs[j].length() || compareNum != strs[j].charAt(i)){
return template.substring(0,i);
}
}
}
return template;
}
时间复杂度:O(mn),其中 m是字符串数组中的字符串的平均长度,n是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次。
空间复杂度:O(1)。使用的额外空间复杂度为常数。