Write a function to find the longest common prefix string amongst an array of strings.
1 private static int MinLength(String[] strs) {
2 int temp = Integer.MAX_VALUE;
3 for(int i=0; i<strs.length;i++){
4 if(temp>strs[i].length())
5 temp = strs[i].length();
6 }
7 return temp;
8 }
9
10 public static String longestCommonPrefix(String[] strs) {
11 if(strs.length==0){
12 return "";
13 }
14 int j = 0;
15 boolean flag = false;
16
17 int length = MinLength(strs);
18
19 while(j<length){
20 int i = 1;
21 while(i<strs.length){
22 int c = strs[0].charAt(j);
23 if(strs[i].charAt(j)==c){
24 i++;
25 }else{
26 flag = true;
27 break;
28 }
29 }
30 if(flag)
31 break;
32 j++;
33 }
34
35 return strs[0].substring(0, j);
36 }
1 private int minlen(String[] strs) {
2 int min = Integer.MAX_VALUE;
3 for(int i=0; i<strs.length;i++)
4 min = Math.min(min,strs[i].length());
5 return min;
6 }
7
8 public String longestCommonPrefix(String[] strs) {
9 if (strs == null || strs.length == 0)
10 return "";
11
12 StringBuilder res = new StringBuilder();
13 int index = 0;
14 int len = minlen(strs);
15 while (index < len){
16 for (int i=1; i<strs.length;i++){
17 if (strs[i].charAt(index) != strs[0].charAt(index))
18 return res.toString();
19 }
20 res.append(strs[0].charAt(index));
21 index++;
22 }
23 return res.toString();
24 }