Write a function to find the longest common prefix string amongst an array of strings.
写一个函数
在字符串数组中
找到最长公共子字符串
高票答案,利用了indexof查找子字符串功能~
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
我的答案从头开始,一个字符一个字符地找~
class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuffer result = new StringBuffer("");
if (strs.length==0)
return result.toString();
for (int i = 0; i < strs[0].length(); i++) {
char thechar = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (strs[j].length() <= i)
return result.toString();
if (strs[j].charAt(i) != thechar)
return result.toString();
}
result.append(thechar);
}
return result.toString();
}
}