编写一个函数来查找字符串数组中最长的公共前缀字符串。
解题思路:
1.利用函数stratsWith()来实现。
2.先对字符串数组进行排序,则数组的最长公共子串一定是最小子串和最大子串之间的公共子串。因为,排序后的最小子串和最大子串有不同字符的可能性最大,且不同字符位置最靠前。
class Solution {
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].startsWith(pre))
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
}
或
public String longestCommonPrefix(String[] strs) {
StringBuilder result = new StringBuilder();
if (strs!= null && strs.length > 0){
Arrays.sort(strs);
char [] a = strs[0].toCharArray();
char [] b = strs[strs.length-1].toCharArray();
for (int i = 0; i < a.length; i ++){
if (b.length > i && b[i] == a[i]){
result.append(b[i]);
}
else {
return result.toString();
}
}
return result.toString();
}