14. Longest Common Prefix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public String longestCommonPrefix(String[] strs) {
String sentinel = strs[0];

int endIndex = -1; // inclusive
for (int i = 0; i < sentinel.length(); i++) {
for (int j = 0; j < strs.length; j++) {
if (i >= strs[j].length() || strs[j].charAt(i) != sentinel.charAt(i)) {
return sentinel.substring(0, endIndex + 1);
}
}
endIndex = i;
}

return sentinel.substring(0, endIndex + 1);
}
}

References

14. Longest Common Prefix