` (strs[i].indexOf(prefix) != 0) ` in find LongestCommonPrefix

Alice :

I read such a solution to LongestCommonPrefix

Longest Common Prefix - LeetCode

enter image description here

 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.

recnac :

The idea of this algorithm is:

  1. first assume the first word is the prefix, and then we will check whether prefix is all other word's prefix.

  2. if strs[i].indexOf(prefix) != 0 means it is not start with prefix. So we should cut down the prefix a little bit (remove the last character), that is: prefix = prefix.substring(0, prefix.length() - 1);

  3. we continuously do this, util all the words checked, or the prefix has been cutted to '' (that is why it is called Horizontal scanning)

Hope that helps you, and comment if you have further questions. : )

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88899&siteId=1