@leetcode最長公共字首
題目
編寫一個函數來查找字元串數組中的最長公共字首。
如果不存在公共字首,傳回空字元串 “”。
示例
輸入: [“flower”,“flow”,“flight”,“fly”]
輸出: “fl”
題解
找相同字首需要互相比較;
可以通過兩兩順次比較來做;
思路流:
0 flower
1 flow
2 flight
3 fly
0 flower
1 flow * flow*
2
3
0
1 flow
2 flight *fl*
3
0
1
2 fl
3 fly **fl**
通過temp來記錄目前string;
初始狀态temp是第一個字元串;
用j來卡住temp的長度;
核心算法:
for(j = 0;j<temp.length() && j<strs[i].length();j++){
if(temp.charAt(j) != strs[i].charAt(j)){
break;
}
}
temp= temp.substring(0,j);
java代碼
class Solution {
public String longestCommonPrefix(String[] strs) {
int i;
int j;
if(strs.length == 0){
return "";
}
String temp= strs[0];
for(i = 1;i<strs.length;i++){//注意字元串長度length(),數組長度length
for(j = 0;j<temp.length() && j<strs[i].length();j++){
if(temp.charAt(j) != strs[i].charAt(j)){
break;
}
}
temp= temp.substring(0,j);//用j卡住temp
}
return temp;
}
}