鏈接:https://leetcode-cn.com/problems/longest-common-prefix/
題目
編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 “”。
示例 1:
輸入: [“flower”,“flow”,“flight”]
輸出: “fl”
示例 2:
輸入: [“dog”,“racecar”,“car”]
輸出: “”
解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z
我的思路
我用的是動態規劃的思想,把數組中的第一個字符串取出來作爲基準,通過一個嵌套循環來遍歷對比第一個字符串和其他字符串所轉化成的字符數組,因爲如果是字符串的公共最長前綴,那肯定也是第一個字符串和與它對比的字符串的最長前綴,只要把他們孤立爲每一次取二者的最長前綴然後統一找出最短的便是公共前綴的真子集,即最長公共前綴。而一個StringBuffer則可以充當每次遍歷所獲得的字符串的緩衝,如果它是最長公共前綴,那麼就返回。
代碼實現
class Solution {
public static String longestCommonPrefix(String[] strs) {
String commonPrev = "";
if(strs.length>0){
//如果數組不爲空,賦值
commonPrev=strs[0];
}
//臨時緩衝
StringBuffer temp = new StringBuffer();
//以第一個字符串爲參照
char[] example = commonPrev.toCharArray();
for(int i=1;i<strs.length;i++){
char[] chs = strs[i].toCharArray();
//遍歷的次數取較小的長度
int length = example.length<=chs.length?example.length:chs.length;
//如果存在空字符串,返回空串
if(length==0) return "";
for(int j=0;j<length;j++){
if(example[j]==chs[j]&&j<length-1){
temp.append(example[j]);
}else{
if(j==length-1&&example[j]==chs[j]){
temp.append(example[j]);
}
if(temp.length()<commonPrev.length()){
commonPrev = temp.toString();
}
temp.delete(0,temp.length());
break;
}
}
}
return commonPrev;
}
}
不足
因爲嵌套了循環,所以太慢了,時間複雜度達到了O(n^2),還是要看看大佬們的優秀解題思路啊。