class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; else if (strs.length == 1) return strs[0]; StringBuilder res = new StringBuilder(); int index = 0; char temp = ' '; boolean flag = true; f1: while (flag) { f2: for (int i = 0; i < strs.length; i++) { if ("".equals(strs[i])) break f1; if (i == 0) temp = strs[i].charAt(index); else if (temp != strs[i].charAt(index)) break f1; else if (i == strs.length - 1) if (temp == strs[i].charAt(index)) res.append(temp); if (index >= strs[i].length() - 1) flag = false; } index++; } return res.toString(); } }
解法二
主要思想
比较前两个字符串,得到公共前缀,与第三个字符串比较,直至公共前缀为空。
运行速度:超过了100%的解答。
内存使用:超过了80.70%的解答。
源码
1 2 3 4 5 6 7 8 9 10 11 12 13
class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String prefix = strs[0]; for (int i = 1; i < strs.length; i++) while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) return ""; } return prefix; } }
classSolution{ public String longestCommonPrefix(String[] strs){ if (strs == null || strs.length == 0) return""; int minLen = Integer.MAX_VALUE; for (String str : strs) minLen = Math.min(minLen, str.length()); int low = 1; int high = minLen; while (low <= high) { int middle = (low + high) / 2; if (isCommonPrefix(strs, middle)) low = middle + 1; else high = middle - 1; } return strs[0].substring(0, (low + high) / 2); }
privatebooleanisCommonPrefix(String[] strs, int len){ String str1 = strs[0].substring(0,len); for (int i = 1; i < strs.length; i++) if (!strs[i].startsWith(str1)) returnfalse; returntrue; } }