find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". (注意要檢查參數數組是否爲空或==null)
==Example==
Input: ["flower","flow","flight"]
Output: "fl"
public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; String shortest = strs[0]; String prefix = ""; for(int i=1; i<strs.length; i++){ if(strs[i].length() < shortest.length()) shortest = strs[i]; } for(int i=0; i<shortest.length(); i++){ int j = 0; for(; j<strs.length; j++){ if(strs[j].charAt(i) != shortest.charAt(i)) break; if(j == strs.length-1) prefix += String.valueOf(shortest.charAt(i)); } if(j != strs.length) break; } return prefix; }
while (!shortest.equals("")){ int j = 0; for (; j<strs.length; j++){ if (!strs[j].startsWith(shortest)){ shortest = shortest.substring(0,shortest.length()-1); break; } } if (j == strs.length) //這裏這個if若是忘寫了就會死循環 return shortest; } return shortest;