1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length < 1) { return ""; }
List<char[]> chars = new ArrayList<>(); int _minLength = strs[0].length(); for (String s: strs) { chars.add(s.toCharArray()); if (_minLength > s.length()) { _minLength = s.length(); } }
List<Character> result = new ArrayList<>(); boolean breaked = false; for (int i = 0; i < _minLength; i++) { char ch1 = chars.get(0)[i]; for (int j = 1; j < strs.length; j++) { if (chars.get(j)[i] != ch1) { breaked = true; break; } } if (breaked) { break; } result.add(ch1); }
if (result.size() == 0) { return ""; } else { StringBuilder sb = new StringBuilder(); for (Character character: result) { sb.append(character); } return sb.toString(); } } }
|