Longest Common Prefix Leetcode
Write a function to find the longest common prefix string amongst an array of strings.
这道题利用stringbuffer的delete方法
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null) { return null; } if (strs.length == 0) { return ""; } StringBuilder s = new StringBuilder(strs[0]); for (int i = 1; i < strs.length; i++) { int j = 0; for (j = 0; j < s.length() && j < strs[i].length(); j++) { if (strs[i].charAt(j) != s.charAt(j)) { s.delete(j, s.length()); break; } } s.delete(j, s.length()); } return s.toString(); } }
topsolution是用substring的
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null) { return null; } if (strs.length == 0) { return ""; } String s = strs[0]; int i = 0; while (i < strs.length) { while (strs[i].indexOf(s) != 0) { s = s.substring(0, s.length() - 1); } i++; } return s; } }
还可以用Arrays.sort的方法
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null) { return null; } if (strs.length == 0) { return ""; } Arrays.sort(strs); for (int i = 0; i < strs[0].length(); i++) { if (strs[0].charAt(i) != strs[strs.length - 1].charAt(i)) { return strs[0].substring(0, i); } } return strs[0]; } }