LintCode 78: Longest Common Prefix

博客围绕求多个字符串的最长公共前缀(LCP)展开,给出了示例,如输入“ABCD”“ABEF”“ACEF”输出“A”等。还介绍了两种解法,一种是使用hash map,给出了代码,另一种是Trie,待完善。

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

  1. Longest Common Prefix
    中文English
    Given k strings, find the longest common prefix (LCP).

Example
Example 1:
Input: “ABCD”, “ABEF”, “ACEF”
Output: “A”

Example 2:
Input: “ABCDEFG”, “ABCEFG” and “ABCEFA”
Output: “ABC”

解法1:hash map
代码如下:

class Solution {
public:
    /**
     * @param strs: A list of strings
     * @return: The longest common prefix
     */
    string longestCommonPrefix(vector<string> &strs) {
        int N = strs.size();
        if (N == 0) return "";
        
        unordered_map<string, vector<string>> hashmap;
        
        for (int i = 0; i < N; ++i) {
            int M = strs[i].size();
            
            for (int j = 0; j < M; ++j) {
                string pre = strs[i].substr(0, j + 1);
                hashmap[pre].push_back(strs[i]);
            }
        }
        
        string result;
        int maxLen = 0;
        
        for (auto h : hashmap) {
            if (h.second.size() == N) {
                if (h.first.size() > maxLen) {
                    maxLen = h.first.size();
                    result = h.first;
                }
            }
        }
        
        return result;
    }
};

解法2: Trie
TBD

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值