LeetCode 14. Longest Common Prefix

本文详细解析了LeetCode第14题“最长公共前缀”的多种解法,包括直接比较、垂直扫描等,提供了清晰的代码示例,帮助读者理解和掌握此题的解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 14. Longest Common Prefix

Description

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

在这里插入图片描述

Note

All given inputs are in lowercase letters a-z.

Code

  • java
class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        if(len == 0) return "";
        int commonLength = 0;
        int minLength = strs[0].length();
        for(int i = 1; i < len; i++) {
            minLength = Math.min(minLength, strs[i].length());
        }
        for(; commonLength < minLength; commonLength++) {
            char ch = strs[0].charAt(commonLength);
            boolean same = true;
            for(int i = 1; i < len; i++) {
                if(strs[i].charAt(commonLength) != ch) {
                    same = false;
                    break;
                }
            }
            if(!same) break;
        }
        return strs[0].substring(0, commonLength);
    }
}
  • Official solution1
  • 按两个之间比较后得到的结果与下一个字符串继续比较。
 public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }        
    return prefix;
}
  • Official Solution2:Vertical scanning
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        for (int i = 0; i < strs[0].length() ; i++){
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j ++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c)
                    return strs[0].substring(0, i);             
            }
        }
        return strs[0];
    }
}

Conclusion

  • 有很多种解法,比如二分,归并等
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值