題目:
最長公共前綴
解法:
比較簡單, 直接拿其中一個(gè)字符串作為對比字符串, 然后從第一位開始往后對比. 如果有不相等的或者是超出字符串長度的, 便認(rèn)為已經(jīng)找到最長子串.
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length < 1){
return "";
}
if(strs.length == 1){
return strs[0];
}
String cmpStr = strs[0];
int count = 0;
// 是否找到最長子串了
boolean isFind = false;
while(count < cmpStr.length()){
char cmpChar = cmpStr.charAt(count);
for(int i=1; i< strs.length; i++){
String str = strs[i];
if( (str.length() == count) || (str.charAt(count) != cmpChar) ){
isFind = true;
break;
}
}
if(isFind){
break;
}
count++;
}
return cmpStr.substring(0, count);
}