LeetCode T14 Longest Common Prefix

题目地址:

中文:https://leetcode-cn.com/problems/longest-common-prefix/
英文:https://leetcode.com/problems/longest-common-prefix/

题目描述:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string “”.

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""

Explanation: There is no common prefix among the input strings.

Constraints:

0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

思路:

求最长公共前缀,思路是垂直扫描,扫描每个字符串的第一个字符,然后继续扫描每个字符串的第二个直到最后。
注意一些特殊情况的处理,比如字符串数组strs是空的,strs只有一个字符串,strs里的字符串是空的等情况。
答案里有个分治的,代码很不错,值得学习。贴在下面代码2了。

题解:

题解1:垂直扫描
class Solution {
    public static String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        StringBuffer buffer = new StringBuffer();
        int i=0,j=0;
        boolean flag = true;
        while(flag){
            i=0;
            while(i+1<strs.length){
                if(j<strs[i].length()&&j<strs[i+1].length()&&strs[i].charAt(j)==strs[i+1].charAt(j))
                    ;
                else flag = false;
                i++;
            }
            if(strs.length==1&&j>=strs[0].length()) flag = false;//只有一个串的时候
            if(!flag) break;
            else if(i>1) buffer.append(strs[i-1].charAt(j));
                else buffer.append(strs[i].charAt(j));
            j++;
        }
        String res = buffer.toString();
        return res;
    }
}
题解2:分治
public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";    
        return longestCommonPrefix(strs, 0 , strs.length - 1);
}

private String longestCommonPrefix(String[] strs, int l, int r) {
    if (l == r) {
        return strs[l];
    }
    else {
        int mid = (l + r)/2;
        String lcpLeft =   longestCommonPrefix(strs, l , mid);
        String lcpRight =  longestCommonPrefix(strs, mid + 1,r);
        return commonPrefix(lcpLeft, lcpRight);
   }
}

String commonPrefix(String left,String right) {
    int min = Math.min(left.length(), right.length());       
    for (int i = 0; i < min; i++) {
        if ( left.charAt(i) != right.charAt(i) )
            return left.substring(0, i);
    }
    return left.substring(0, min);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值