给k个字符串,求出他们的最长公共前缀(LCP)
样例
在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 为 "A"
在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"
广度优先:
public class Solution {
/*
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
// write your code here
if (strs.length == 0)
return "";
String base = strs[0];
StringBuilder re = new StringBuilder();
for (int i = 0; i < base.length(); ++i) {
char c = base.charAt(i);
for (int j = 1; j < strs.length; ++j) {
if (i >= strs[j].length() || strs[j].charAt(i) != c)
return re.toString();
}
re.append(c);
}
return re.toString();
}
}