[Leetcode 14, Easy] Longest common prefix

Problem:

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

Analysis:

Find the shortest string in the vector. Compare this one with other strings. If it is not a prefix of some string in the vector, use its prefix (for a length looping from its size to 0) to replace the original string. This is valid, because a common prefix cannot be longer than the shortest string in the vector.


We do not repeat previous comparisons, since a prefix of the shortest string must be the common prefix of other strings. Then, the running time is O(kn), where k the size of longest common prefix.

Solutions:

C++:

string longestCommonPrefix(vector<string> &strs) {
        if(strs.empty())
            return "";
            
        int minIndex = 0;
        int minSize = strs[minIndex].size();
        for(int i = 0; i < strs.size(); ++i)
            if(strs[i].size() < minSize) {
                minIndex = i;
                minSize = strs[minIndex].size();
            }
        
        string prefix = strs[minIndex];
        int prefixLen = prefix.size();
        for(int i = 0; i < strs.size(); ++i) {
            if(i == minIndex)
                continue;

            if(strs[i].substr(0, prefixLen) != prefix.substr(0, prefixLen))
                for(int j = 1; j <= prefixLen; ++j)
                    if(j == prefixLen)
                        return "";
                    else if(strs[i].substr(0, prefixLen - j) == prefix.substr(0, prefixLen - j)) {
                        prefixLen -= j;
                        break;
                    }
        }
        
        return prefix.substr(0, prefixLen);
    }


Java:


Python:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值