1. 题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
2. 解题
这个题目比较简单,整个数组最长的公共前缀,一定是不能超过最短的数据长度的。
用最短的字符串去和其他字符进行比较,如果都没有比较得到就是空返回:""
。
class Solution {
public String longestCommonPrefix(String[] strs) {
String stringBuilder = "";
int s = -1;
if (strs.length == 1) {
return strs[0];
} else if (strs.length > 1) {
int max = 0;
stringBuilder = strs[0];
for (int i = 1; i < strs.length; ++i) {
max = Math.min(stringBuilder.length(), strs[i].length());
if (max > 0) {
int j = 0;
for (; j < max; ++j) {
if (stringBuilder.charAt(j) != strs[i].charAt(j)) {
break;//结束本次循环
}
}
if (j >= 0) {
if (s > j || s == -1) {
s = j;
}
} else {
return "";
}
} else {
return "";
}
}
if (s >= 1) {
return stringBuilder.substring(0, s);
} else {
return "";
}
} else {
return "";
}
}
}
执行用时: 1 ms
内存消耗: 39.2 MB
上面自己实现时,过程比较清晰,但是代码也太长了。通过其他大神们的调整方法:
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 1) //题目标注 1 <= strs.length <= 200 所以我们只需要考虑为1,直接返回
return strs[0];
String s = strs[0]; //得到一个标准比较值
if (s.length() == 0) {
return "";
}
for (int i = 1; i < strs.length; ++i) {
//从第二位数开始进行比较
if (strs[i].length() == 0) {
return "";//只要有一个字符
}
while (!strs[i].startsWith(s)) { //在这一步的时候,注意两个String位置
//截取
s = s.substring(0, s.length() - 1);
if (s.length() == 0) {
return "";
}
}
}
return s;
}
}
执行用时: 0 ms
内存消耗: 39.2 MB
瞬间效率要提高了很多。而且代码比我自己写的更清晰了。上面代码添加了注释。
如果不想使用系统的startsWith 函数,可以试试官方的示例(纵向扫描):
从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int length = strs[0].length();
int count = strs.length;
for (int i = 0; i < length; i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < count; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
}
}
官方还有很多其他的写法,也有很多大神的方法。这里只是记录一下我当初的选择。
评论区