题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
思路
遍历第一个字符串,循环变量为i
依次判断 后面每一个字符串的第i个字符是否=第一个字符串的第i个字符
注意:为了避免越界,i为最短的字符串的长度
代码
public class Main {
public static void main(String[] args) {
String[] strs = {"cir", "car"};
System.out.println(longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
//获取最小的元素长度
int min = strs[0].length();
for (String a :
strs) {
if (a.length() < min) {
min = a.length();
}
}
String result = "";
if (strs.length >= 2) {
for (int i = 0; i < min; i++) {
boolean ifStop = false;
for (int j = 1; j < strs.length; j++) {
//第j个元素的第i个字符是否和temp相等
if (strs[j].charAt(i) == strs[0].charAt(i))
continue;
else {
ifStop = true;//是否因为某一列上的不满足而终止
break;
}
}
if (ifStop)
break;
else result=result+String.valueOf(strs[0].charAt(i));;
}
} else if (strs.length == 1) result = strs[0];
else result = "";
return result;
}
}