Write a function to find the longest common prefix string amongst an array of strings.
public class Solution { public String longestCommonPrefix(String[] strs) { String compare =""; if(strs.length == 0) return compare; compare = strs[0]; for(int i = 1; i < strs.length; i++){ int j = 0; while(j < compare.length() && j < strs[i].length()){ if(compare.charAt(j) != strs[i].charAt(j)){ break; } j++; } compare = strs[i].substring(0,j); } return compare; } }
方法二: ref:http://www.cnblogs.com/feiling/p/3159771.html
依次比较每个字符串的相应位置的字符,直到遇到不匹配项。可以减少不必要的比较
public class Solution { public String longestCommonPrefix(String[] strs) { String compare = ""; if(strs.length == 0) return compare; int k = 0; while(true){ char p = ' '; int i; for(i = 0; i < strs.length; i++){ if(k == strs[i].length()) break; if(i == 0) p = strs[i].charAt(k); if(p != strs[i].charAt(k)) break; } // 出for循环后,检查是循环结束还是break跳出的循环 // 如果是break跳出的循环,就break跳出while if(i != strs.length) break; compare += p; k++; } return compare; } }