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