题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
解法:
方法一、从前向后遍历比较
1.在所有的strs元素中找到长度最小的一个,长度设为minLen,最长公共前缀不可能比minLen更长,所以以minLen为基准遍历。
2.i从零开始向右横向遍历,以chi作为指针指向当前遍历到的strs[0]中下标i对应的字符,即chi=strs[0].chatAt(i)。
3.在横向遍历的同时,变量j从1开始,遍历strs中的所有字符串,以chj作为指针指向当前所遍历到的strs中的字符串中下标为i的字符,即chj=strs[j].charAt(i)。
4.对每一个chi和chj比较,一旦两者不相等,说明公共前缀的部分已经结束,停止遍历并切割出公共前缀进行返回。
例如:对于strs=["flow","flower","flight"]:
strs[0]="flow", strs[1]="flower", strs[2]="flight", minLen=4
i从0到4开始横向遍历:
i=0, chi=strs[0].chatAt(i)='f':
j从1开始纵向遍历:
j=1, chj=strs[j].charAt(i)='f', chi=chj,继续遍历
j=2, chj=strs[j].charAt(i)='f', chi=chj, 继续遍历
j第一次遍历完,此时最长公共前缀为“f”, i++:
i=1, chi=strs[0].chatAt(i)='l':
j再次从1开始纵向遍历:
j=1, chj=strs[j].charAt(i)='l', chi=chj,继续遍历
j=2, chj=strs[j].charAt(i)='l', chi=chj, 继续遍历
j第二次遍历完,此时最长公共前缀为“fl”, i++:
i=2, chi=strs[0].chatAt(i)='o'
j再次从1开始纵向遍历:
j=1, chj=strs[j].charAt(i)='0', chi=chj,继续遍历
j=2, chj=strs[j].charAt(i)='i', chi !=chj, 此时已经出现不相等情况了,所以最长公共前缀已经结束,遍历停止。
最后的结果,最长公共前缀为“fl”。
代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int minLen = 201;
for (String str : strs) {
if (str == null || str.isEmpty()) {
return "";
}
minLen = Math.min(minLen, str.length());
}
for (int i = 0; i < minLen; i++) {
char chi = strs[0].charAt(i);
for (int j = 1; j < strs.length && strs[j] != null; j++) {
char chj = strs[j].charAt(i);
if (chj != chi) {
return strs[0].substring(0, i);
}
}
}
return strs[0].substring(0, minLen);
}
}
方法二、排序后比较第一个和最后一个字符串
判断不为空后,先利用sort排序算法对strs中的所有字符串进行排序,此时所有字符串是按照从小到大排序的,比较第一个字符串和最后一个字符串所拥有的公共前缀即可。
代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
if (strs.length == 0) {
return "";
}
for (String str : strs) {
if (str == null || str.isEmpty()) {
return "";
}
}
Arrays.sort(strs);
if (strs[0] == null || strs[0].isEmpty()) {
return "";
}
String ans = "";
for (int i = 0; i < strs[0].length() && i < strs[n - 1].length(); ++i) {
if (strs[0].charAt(i) == strs[n - 1].charAt(i)) {
ans += strs[0].charAt(i);
} else {
break;
}
}
return ans;
}
}