链接:https://leetcode-cn.com/problems/longest-common-prefix
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
//思路:依次遍历字符串数组,用第一个字符串匹配,没有的话取第一个字符串的0到倒数第二位,依次递减。
class Solution {
public String longestCommonPrefix(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;
}
}
indexOf函数的用法参考:
https://blog.csdn.net/wust_lh/article/details/81502256