Compare words by words to find the longest common prefix.
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
if(n == 0)
return ""; // corner case
String com = strs[0];
for(int i = 1; i < n; i++) {
int len = Math.min(com.length(), strs[i].length());
int p = 0;
while(p < len && com.charAt(p) == strs[i].charAt(p))
p++;
com = com.substring(0, p);
}
return com;
}
Another way is to try to find the first character that differs.
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
if(n == 0)
return ""; // corner case
int len = strs[0].length();
int i = 0;
for(i = 0; i < len; i++) {
for(int j = 0; j < n; j++) {
if(strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) // the first position that differs
return strs[0].substring(0, i);
}
}
return strs[0].substring(0, i);
}
没有评论:
发表评论