题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例
输入: ["flower","flow","flight"]
输出: "fl"
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
代码
方法一:
- 一个显而易见的结论是:在字符串数组里任取两个字符串求得的最长公共前缀,一定是小于等于整个字符串数组的最长公共前缀的。
- 设立一个比较基字符串
result
,先赋值为字符串数组的第一个字符串,其他的字符串挨个按位与之比较,求得最长公共前缀替换掉result
。
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
String result = strs[0];
for (int i = 1; i < strs.length; ++i) {
int j = 0;
for (; j < result.length() && j < strs[i].length(); ++j) {
if (result.charAt(j) != strs[i].charAt(j)) {
break;
}
}
result = result.substring(0, j);
}
return result;
}
}
方法二
- 先找到长度最短的字符串,
- 遍历字符串数组,检查最短字符串是否被从头包含于其他字符串,如果没有,最短字符串去掉末位继续检查
注意:string.indexOf("")
会返回0
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length < 1 || strs == null) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
//find the shortest String
int shortest = 0;
int len = strs[0].length();
for (int i = 1; i < strs.length; i++) {
int curLen = strs[i].length();
if (curLen < len) {
len = curLen;
shortest = i;
}
}
//find the longest common prefix
String sub = strs[shortest];
for (int i = 0; i < strs.length; i++) {
while (strs[i].indexOf(sub) != 0) {
sub = sub.substring(0, sub.length()-1);
}
}
return sub;
}
}