題目:
編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""。
示例 1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z 。
分析:
1.數組中放的是字符串,每個字符串也有自己的長度
2.需要找到數組中最短的字符串,因為其他字符超了的不可能和這個字符再有交集
3.定1,讓后面的字符和第一個字符的每一個元素比較,相同的返回。
代碼如下:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0){
return "";
}
if(strs.length == 1){
return strs[0];
}
int len = strs[0].length();
for(String str:strs){
len = Math.min(len,str.length()); //得到字符數組里面最短字符的長度
}
if(len == 0){ //其中的一個字符為空的情況
return " ";
}
StringBuffer res = new StringBuffer(len);
//每個字符只需要遍歷到最小長度即可,因為大於最小長度字符的那一部分不可能有公共
for(int j = 0; j < len;j++){
for(int t= 0;t < strs.length;t++){
if(strs[t].charAt(j) != strs[0].charAt(j)){ //每個與第一個字符開始比較,也就是與下標為0的字符的元素比較。
return res.toString();
}
}
res.append(strs[0].charAt(j)); //相同就加進結果集
}
return res.toString();
}
}
我在LeetCode看到一種解法,時間復雜度看着很小,因為它利用了Java特有的函數。但是函數內部的時間復雜度就不明而已了。這個代碼也是比較簡潔的。我們來看看:
代碼如下:
class Solution {
public String longestCommonPrefix(String[] strs) {
String ret = "";
if(strs.length == 0) return ret;
if(strs.length == 1) return strs[0];
ret = strs[0];
for(int i = 1; i < strs.length; i++){
while (!strs[i].startsWith(ret)){ //判斷與第一個元素的相同字符
ret = ret.substring(0, ret.length()-1);
if (ret.length() == 0){
return "";
}
}
}
return ret;
}
}
