编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 查找字符串数组中的最长公共子串
*/
public String longestCommonPrefix(String[] strs){
// 如果输入参数为空返回空串
if (strs==null||strs.length==0){
return "";
}
// 第一个数组元素
String prefix=strs[0];
for (int i = 1; i < strs.length; i++) {
// 长度最短的字符
int length = Math.min(prefix.length(),strs[i].length());
int j;
int index=0;
for (j = 0; j < length; j++) {
if (prefix.charAt(j)==strs[i].charAt(j)){
index++;
}
}
// 截取字符串
prefix=prefix.substring(0,index);
}
return prefix;
}