leetcode14最长公共前缀

题目来源:题目

题目

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

 

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

 

示例 1:

 

输入: ["flower","flow","flight"]

输出: "fl"

示例 2:

 

输入: ["dog","racecar","car"]

输出: ""

解释: 输入不存在公共前缀。

说明:

 

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

思路

思路一(横向比较)

       求得两个字符串的公共前缀,由于它们所有的公共前缀也是任意多个字符串的公共前缀,所以可以用该公共前缀在和其他字符串求公共前缀。

思路二(纵向比较)

       可以对字符矩阵的每一列比较是否完全相同,如果这一列都相同,则比较下一列,否则公共前缀就到当前列结束。

思路三(分治)

       由于公共的前缀比较有结合律,所以可以先两两得到互相的公共前缀,然后再两两将得到的公共前缀比较自己的公共前缀。利用分治的思想最终得到所有的公共前缀。

代码

思路一代码

public static String longestCommonPrefix(String[] strs) {
    if(strs == null || strs.length == 0)return "";
    String common = strs[0];
    for(int i = 1;i < strs.length;i++){
        common = commonString(common,strs[i]);
    }
    return common;
}

public static String commonString(String s1,String s2){
    String res = "";
    if(s1.equals("") || s2.equals(""))return "";
    int i = 0;
    while(i < s1.length() && i < s2.length()){
        if(s1.charAt(i) == s2.charAt(i))i++;
        else break;
    }
    return s1.substring(0,i);
}

思路二代码

public static String longestCommonPrefix(String[] strs){
    if(strs == null || strs.length == 0)return "";
    int minLength = Integer.MAX_VALUE;
    for(int j = 0;j < strs.length;j++){
        if(strs[j].length() < minLength)minLength = strs[j].length();
    }
    int i = 0;
    for(i = 0;i < minLength;i++){
        boolean flag = true;
        for(int j = 1;j < strs.length;j++){
            if(strs[j].charAt(i) != strs[0].charAt(i)){
                flag = false;
                break;
            }
        }
        if(!flag)break;
    }
    return strs[0].substring(0,i);
}

 

思路三代码

public static String longestCommonPrefix(String[] strs){

        if(strs == null || strs.length == 0)return "";

        return commonPrefix(strs,0,strs.length - 1);

    }

    public static String commonPrefix(String[] strs,int left,int right){

        if(right - left <= 1)return commonString(strs[left],strs[right]);

        int mid = (left + right) / 2;

        return commonString(commonPrefix(strs,left,mid),commonPrefix(strs,mid + 1,right));

    }

    public static String commonString(String s1,String s2){

        String res = "";

        if(s1.equals("") || s2.equals(""))return "";

        int i = 0;

        while(i < s1.length() && i < s2.length()){

            if(s1.charAt(i) == s2.charAt(i))i++;

            else break;

        }

        return s1.substring(0,i);

    }

 

总结

思路一时间复杂度为O(MN)

思路二时间复杂度为O(MN)

思路三时间复杂度为O(MN)

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值