LeetCode 字符串专题(一)

LeetCode 字符串专题 <c++>

\([5]\) Longest Palindromic Substring

最长回文子串

\([28]\) Implement strStr()

要求实现c++中strstr()函数。
解法一:暴力 时间复杂度 \(O(nm)\)
解法二:KMP,时间复杂度 \(O(n+m)\),附代码

class Solution {
public:
    int strStr(std::string haystack, std::string needle) {
        return kmp(haystack.c_str(), needle.c_str());
    }

private:
    static void compute(const char *parttern, int next[]) {
        int i;
        int j = -1;
        const int m = strlen(parttern);
        next[0] = j;
        for (i = 1; i < m; i++) {
            while (j > -1 && parttern[j + 1] != parttern[i]) j = next[j];
            if (parttern[i] == parttern[j + 1]) j++;
            next[i] = j;
        }
    }

    static int kmp(const char *text, const char *parttern) {
        int i;
        int j = -1;
        const int n = strlen(text);
        const int m = strlen(parttern);
        if (m == 0) return 0;
        int *next = (int *) malloc(sizeof(int) * m);
        compute(parttern, next);
        for (i = 0; i < n; i++) {
            while (j > -1 && parttern[j + 1] != text[i]) j = next[j];
            if (text[i] == parttern[j + 1]) j++;
            if (j == m - 1) {
                free(next);
                return i - j;
            }
        }
        free(next);
        return -1;
    }
};

[\(49\)] Group Anagrams

将每个字符串的字符排完序后,若两个字符串相同,则构成原串的字母种类及数量都相同,即属于同一组‘Anagrams’。
hash,时间复杂度 \(O(n)\)

class Solution {
public:
    std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string> &strs) {
        std::unordered_map<std::string, std::vector<std::string>> ump;
        for (auto i = strs.begin(); i != strs.end(); i++) {
            auto key = *i;
            std::sort(key.begin(), key.end());
            ump[key].push_back(*i);
        }
        std::vector<std::vector<std::string>> res;
        for (auto i = ump.begin(); i != ump.end(); i++) {
            res.push_back(i->second);
        }
        return res;
    }
};

转载于:https://www.cnblogs.com/NeilThang/p/10430677.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值