Poison

14. Longest Common Prefix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String longestCommonPrefix(String[] strs) {
int endIndex = 0; // exclusive
String sentinel = strs[0];
while (endIndex < sentinel.length()) {
for (int i = 1; i < strs.length; i++) {
String str = strs[i];
if (endIndex == str.length() || str.charAt(endIndex) != sentinel.charAt(endIndex)) {
// 无法到达 endIndex 或 endIndex 上的字符不相等
// 注意此处不能使用 break, 因为 break 只能跳出一层
return sentinel.substring(0, endIndex);
}
}

endIndex++;
}

return sentinel.substring(0, endIndex);
}
}
Reference

14. Longest Common Prefix