I read such a solution to LongestCommonPrefix
Longest Common Prefix - LeetCode
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++)
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
return prefix;
}
As for while (strs[i].indexOf(prefix) != 0)
, if prefix
is not empty, the expression will constantly return True;
How could conclude that prefix = prefix.substring(0, prefix.length() - 1);
, I assumed the while (strs[i].indexOf(prefix) != 0)
did nothing.
The idea of this algorithm is:
first assume the first word is the
prefix
, and then we will check whetherprefix
is all other word's prefix.if
strs[i].indexOf(prefix) != 0
means it is not start withprefix
. So we should cut down the prefix a little bit (remove the last character), that is:prefix = prefix.substring(0, prefix.length() - 1);
we continuously do this, util all the words checked, or the prefix has been cutted to
''
(that is why it is calledHorizontal scanning
)
Hope that helps you, and comment if you have further questions. : )