/*
题目:最长公共前缀 simple
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
思路:
1)每条字符串对应index比较,不相等时直接返回已相等的部分:本题采用
2)字符串两两比较,先得到str1和str2的公共前缀ans,再得到ans和str3的公共前缀,赋值给ans
*/
package leetCode.Other;
public class lc_other_14_longestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0)
return "";
char cur = ' ';
String res = "";
for (int i = 0; i < strs[0].length(); i++) {
cur = strs[0].charAt(i);//第一条字符串的i位置字符
for (int j = 1; j < strs.length; j++) {//与后面的字符串比较i位置的字符
// 超出范围或不相等直接返回已相等的res部分
if (strs[j].length() - 1 < i || strs[j].charAt(i) != cur) {
return res;
}
}
// 当前位置相等就加入到res中
res += cur;
}
return res;
}
}