Write a function to find the longest common prefix string amongst an array of strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuffer result = new StringBuffer();
if (strs == null || strs.length < 1) return "";

Arrays.sort(strs);
char[] first = strs[0].toCharArray();
char[] last = strs[strs.length - 1].toCharArray();

for (int i = 0; i < first.length && i < last.length; i++){
if (first[i] == last[i]){
result.append(first[i]);
}else{
break;
}
}

return result.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public 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].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder();
if (strs != null && strs.length > 0) {
sb.append(strs[0]);
for (int i = 0; i < strs.length; i++) {
String cur = strs[i];
sb.delete(Math.min(cur.length(), sb.length()), sb.length());
for (int j = 0; j < sb.length(); j++) {
if (sb.charAt(j) != cur.charAt(j)) {
sb.delete(j, sb.length());
}
if (sb.length() == 0) return "";
}
}
}
return sb.toString();
}
}