題目:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
比較所有String中最小相同開頭的字串.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static String longestCommonPrefix(String[] strs) { if(strs.length == 0) return ""; String res = strs[0]; for(int i=1;i<strs.length;i++){ String tempStr = strs[i]; int min_size = tempStr.length() > res.length() ? res.length() : tempStr.length(); res= res.substring(0,min_size); for(int j=0;j<min_size;j++){ if(tempStr.charAt(j)!= res.charAt(j)){ res = res.substring(0, j); break; } } } return res; } |
文章標籤
全站熱搜