I am trying to solve a question which says: Write a function to find the longest common prefix string amongst an array of strings.
Input:
["baab","bacb","b","cbc"]
Inside while loop, if i use break it returns an empty string which is correct answer:
""
But if i use break, it returns:
"ba"
Below is my code:
class Solution {
public String longestCommonPrefix(String[] strs) {
String first=strs[0];
for(int i=1;i<=strs.length-1;i++){
char[] c1 = first.toCharArray();
char[] c2 = strs[i].toCharArray();
int index=0;
first="";
int len=0;
if(c1.length<c2.length)
len=c1.length;
else
len=c2.length;
if(len==0){
return first;
}
while(index<=len-1){
if(c1[index]==c2[index]){
first=first+c1[index];
}else{
**return first;**
}
index++;
}
}
return first;
}
}
As per my understanding, when we return inside a while loop(which is the inner loop here), it should come out of that particular loop and not from the outer for loop, similar to break. Please help me understand why it is coming out of the for loop here.