14th question from LeetCode
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String carry = "";
carry = strs[0];
//set i to traverse the String array
for (int i = 1; i < strs.length; i++) {
while(strs [i].indexOf(carry) != 0){
if (carry.charAt(0) != strs [i].charAt(0)) break;
//this loop will continue while the carry string is not included
//in the current string && overlaps from the beginning
carry = carry.substring(0, carry.length()-1);//cut short char by char
if (carry.isEmpty()) break;
//this means carry is not included in the current string at all
}
}
return carry;
}
so the idea we use here is to set the first element of the strs[ ] as the carry string , then to shorten the in the loop while the carry string is not only included in the current string but also overlaps from the begging
Thus the carry string which is the first sting of the array will be shorten again and again to fit the requirements
of course it is ok for us to use other ideas to fix this question , just be careful the arrays out of bounds error if you wants to use double “for” loop
god damn it, this is my first algorithm analysis blog and I don’t know what the hell I’m talking.
plus : forgive my funny English…