Problem
Write a function to find the longest common prefix string amongst an array of strings.
Note
我的思路是用StringBuilder
对strs
中的字符串逐个遍历第i
位的字符,如果都相同,就把这个字符存入sb
,否则返回已有的sb
字符串。
for
循环的条件:i
的值不能大于str.length()-1
。 Solution
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; int len = strs[0].length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { for (String str: strs) { if (str.length() < i+1 || str.charAt(i) != strs[0].charAt(i)) { return sb.toString(); } } sb.append(strs[0].charAt(i)); } return sb.toString(); }}
Update 2018-8
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; Arrays.sort(strs); //compare strs[0] and strs[strs.length-1], since they should be the most different pair int i = 0, len = strs.length; while (i < Math.min(strs[0].length(), strs[len-1].length()) && strs[0].charAt(i) == strs[len-1].charAt(i)) { i++; } return strs[0].substring(0, i); }}