Leetcode优化:Longest Common Prefix

本文介绍了一种寻找字符串列表中最长公共前缀的高效算法,包括直觉方法和使用Trie树的方法,详细分析了两种方法的时间复杂度和空间复杂度。

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

Longest Common Prefix


A straight method for this problem is the brute force by enumerating the length of the prefix from 0, and ends until we find the longest common prefix. 

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int start=0;
        int len=0;
        if(strs.size()==0) return "";
        int minLen=strs[0].length();
        
        for(int i=0; i<strs.size(); i++){  //An important observation to accelerate the process 
            if(minLen>strs[i].length())
                minLen=strs[i].length();
        }
        int i;
        for(i=0; i<minLen; i++){
            for(int j=1; j<strs.size(); j++){
                if(strs[j][i]!=strs[j-1][i]){ //break if the condition is not satisfied
                    len=i-start;
                    return strs[0].substr(start, len);
                }
            }
        }
        len=i-start;
        return strs[0].substr(start, len);
    }
};

This time complexity is O(m*l) where l is the minimum length of the string, and the space complexity is O(1)


Another method for finding the longest common prefix is the trie tree, which results in O(n) in time complexity and O(n) in space, as well.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值