- 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。
提示:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
/**
* 暴力解法:
* 数组第一个字符串为基准,向后遍历保留相同字串。
*/
if (strs.length == 0) {
return "";
} else {
String tempStr = strs[0];
for (int i = 1; i < strs.length; i++) {
//两个比较的字符串中最长的相同前缀的索引
int index = 0;
//下一个要比较的字符串
String otherStr = strs[i];
int tLength = tempStr.length();
int oLength = otherStr.length();
for (int j = 0; j < tLength; j++) {
//长度短的字符串遍历结束
if (j >= oLength) {
index = j;
break;
}
//判断
if (tempStr.charAt(j) != otherStr.charAt(j)) {
index = j;
break;
}
index = j + 1;
}
tempStr = tempStr.substring(0, index);
}
return tempStr;
}
}
}