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
| class Solution {
public String longestCommonPrefix(String[] strs) { String ans = strs[0]; for (int i = 1; i < strs.length; i++) { String str = strs[i]; int index = pubSubStringIndex(ans, str); if (index == -1) return ""; ans = ans.substring(0, index); } return ans; }
private int pubSubStringIndex(String ori, String dest) { if (dest.length() < ori.length()) { String tmp = dest; dest = ori; ori = tmp; } for (int i = 0; i < ori.length(); i++) { if (ori.charAt(i) != dest.charAt(i)) { return i; } } return ori.length(); } }
|