Home > Back-end >  Leetcode longest common prefix
Leetcode longest common prefix

Time:11-22

I searched other posts, and this solution has never been discussed, so it's not a duplicate. I am having a hard time following this solution. I understand we set a prefix, and loop through the remainder of the array and keep chopping the prefix until prefix fully exists in each string but why are we doing strs[i].indexOf(output) != 0 in the while loop? If someone can please walk me through this, I would really appreciate it.

public String longestCommonPrefix(String[] strs) {
    if(strs.length == 0) {
        return "";
    }
    String output = strs[0];
    for(int i = 1; i < strs.length; i  ) {
        while(strs[i].indexOf(output) != 0) {
            output = output.substring(0, output.length() - 1);
        }
    }
    return output;
}

CodePudding user response:

Much more understandable (and efficient) would be to use "not startWith."

    while (!strs[i].startsWith(output)) {
        output = output.substring(0, output.length() - 1);
    }

indexOf would also search at other positions for a substring equal to output.

This would be more readable as "as long as strs[i] does not start with the prefix, shorten the prefix by 1. An empty prefix (output) would exit the loop. (You might then also break out of the for loop.)

CodePudding user response:

!= 0 means that the prefix string did not start at the beginning of the string. If the index > 0 it was further into the string. If it was -1 it didn't exist in the string at all. If it was == 0 it started at the beginning.

Notice that the while loop keeps backing up using substring until a prefix matches the beginning. Then it exits the while loop. Then it continues to see if the next string contains the first and backs up until they share an equal prefix. This continues until either a longest common prefix is returned or an empty string.

  •  Tags:  
  • java
  • Related