• strs[0] must be a superset of final prefix.
  • Check all other strings if they contain strs[0]; if not, substring it until satisfied.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String pre = strs[0];

for (int i = 1; i < strs.length; ++i) {
while (strs[i].indexOf(pre) != 0) {
pre = pre.substring(0, pre.length() - 1);
}
}

return pre;
}
}