This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.string; | |
/** | |
* Solution1: select first str as prefix, compare every char with second until not equals one. substring | |
* loop to the last one, then we will get common prefix. | |
* | |
* Solution2: compare first char with every str, if works, second char... | |
* | |
* use j == 0 to optimize. | |
* | |
* @author jeffwan | |
* @date Apr 15, 2014 | |
*/ | |
public class LongestCommonPrefix { | |
public String longestCommonPrefix(String[] strs) { | |
if (strs == null || strs.length == 0) { | |
return ""; | |
} | |
String prefix = strs[0]; | |
for (int i = 1; i < strs.length; i++) { | |
int j = 0; | |
while (j < prefix.length() && j < strs[i].length() && strs[i].charAt(j) == prefix.charAt(j)) { | |
j++; | |
} | |
if (j == 0) { | |
return ""; | |
} | |
prefix = prefix.substring(0, j); | |
} | |
return prefix; | |
} | |
} |
No comments:
Post a Comment