I'm working on a problem - Longest Common Prefix - using Java, for this problem I must return the longest common prefix when given an array of Strings, for example an array of ["ale", "Altamonte", "alligator"] would return the Longest Common Prefix "al". One of the answers given for this problem was provided and I have posted it below, however I do not understand the conditional statement within the while loop, which is while (strs[i].indexOf(prefix) != 0)
. When I try to understand this conditional statement I perceive it as if parameter strs at index i, which can only be 1 through strs.length -1
, why put .indexOf(prefix) != 0
? when I do a print out statement of System.out.println(strs[i].indexOf(prefix));
I get value of -1. I perceive this as some way for the loop to iterate backwards from strs[i]
until the method finally gets to the longest common prefix? I also see that the variable prefix
is equal to strs[0]
so is the while loop conditional saying that since strs[i]
cannot go to 0 then we get value of -1? I hope this question makes sense, I'm just struggling to understand this conditional statement and if anyone could help me understand how this code below is actually working I would very much appreciate the knowledge! many sincere thanks for any help given!
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) {
// System.out.println("Confused by this--> " + strs[i].indexOf(prefix));// this prints out -1 and im not sure why..
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
return prefix;
}