Write a function to find the longest common prefix string amongst an array of strings.
1 public class Solution { 2 public String longestCommonPrefix(String[] strs) { 3 if (strs == null || strs.length == 0) { 4 return ""; 5 } else if (strs.length < 2) { 6 return strs[0]; 7 } 8 9 String r = strs[0]; 10 int index = r.length(); 11 for (int i = 1; i < strs.length; i++) { 12 int j = 0; 13 for (; j < strs[i].length() && j < index; j++) { 14 if (strs[i].charAt(j) != r.charAt(j)) { 15 break; 16 } 17 } 18 if (j == 0) { 19 return ""; 20 } 21 index = j; 22 } 23 24 return r.substring(0, index); 25 } 26 }

浙公网安备 33010602011771号