题目:最长公共前缀
要求:编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""
。
例如 :
输入:["flower","flow","flight"] ["dog","racecar","car"]
输出:"fl" ""
题解代码如下:
class Solution {
private String longestCommonPrefix(String[] strs) {
if (null == strs || strs.length == 0) {
return "";
}
String longestCommonPrefix = strs[0];
for (int i = 1; i < strs.length; i++) {
int index = 0;
String cur = strs[i];
for (int j = 0; j < longestCommonPrefix.length(); j++) {
if (j < cur.length() && longestCommonPrefix.charAt(j) == cur.charAt(j)) {
index++;
} else {
longestCommonPrefix = longestCommonPrefix.substring(0, index);
break;
}
}
}
return longestCommonPrefix;
}
}
我的题解有点复杂化了,看看下面这个吧
class Solution {
private String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0){
return "";
}
String reg = strs[0];
for (String str : strs) {
while (!str.startsWith(reg)) {
if (reg.length() == 1) {
return "";
}
reg = reg.substring(0, reg.length() - 1);
}
}
return reg;
}
}