leetcode刷题之Longest Common Prefix(14)

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:

所有输入只包含小写字母 a-z 。

思路:假设第一个字符串就是最长前缀,依次和剩下的所有字符串对比,如果不是的话,依次减去一个字符再循环对比一遍,直到找到最大前缀或者pre为"",String.indexOf("") = 0

代码:

Java

public static String solution(String[] strs){
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0) {
pre = pre.substring(0, pre.length() - 1);
}
i++;
}
return pre;
}

猜你喜欢

转载自www.cnblogs.com/Simon-cat/p/10163325.html