输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:“”
解释:输入不存在公共前缀。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public static void main(String[] args) {
String[] strs = new String[]{"owew","flow","flight"};
System.out.println(longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
//先前两个字符串比较,之后用公共前缀和后面的字符串比较
String st1 = strs[0];
int count = strs.length;
for (int i = 1; i < count; i++) {
//递归调用
st1 = compare(st1, strs[i]);
if (st1.length()==0){
break;
}
}
return st1;
}
public static String compare(String st1, String st2) {
//选出最小值用来控制循环次数
int length = Math.min(st1.length(), st2.length());
int index = 0;
for (int i = 0; i < length; i++) {
if (st1.charAt(i) == st2.charAt(i)) {
index++;
}else{
//防止出现{“cir”,“car”}的情况,如果不加break,则会出现输出结果为“cr”,这是因为就算出现字符不匹配,
//但是循环不会停止index依然自增
break;
}
}
//返回公共前缀
return st1.substring(0, index);
}