Leetcode 30. 与所有单词相关联的字串

利用kmp记录words中每一个字符串在s中的所有匹配位置
为防止超内存,对words进行排序,并进行编号(相同的字符串为同一id),并记录每一id的出现次数
然后暴力搜索s串每一个位置是否符合要求

class Solution {
public:
    int nextval[100005];
    vector<int> A[100005];
    void get_nextval(string s) {
        int i = 0, x = -1; nextval[i] = x;
        while (i < s.size()) {
            if (x == -1 || s[i] == s[x]) nextval[++i] = ++x;
            else x = nextval[x];
        }
    }
    void strStr(string haystack, string needle, int k) {
        get_nextval(needle);
        int i = 0, j = 0;
        while (i < (int)haystack.size()) {
            if (j == -1 || haystack[i] == needle[j]) ++i, ++j;
            else j = nextval[j];
            if (j == (int)needle.size()) {
                A[i - needle.size()].push_back(k);
                j = nextval[j - 1];
                --i;
            }
        }
    }
    int L[100005], n[100005], AA[100005];
    bool _ok(int index, int cnt) {
        if (!cnt) return true;
        for (int i = 0; i < A[index].size(); ++i) {
            int x = A[index][i];
            if (AA[x]) {
                --AA[x];
                if (_ok(index + L[x], cnt - 1)) return true;
                ++AA[x];
            }
        }
        return false;
    }
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> ans;
        sort(words.begin(), words.end());
        int h = 0, id = 0;
        if (!words.size()) return ans;
        for (int i = 0; i < words.size(); ++i) {
            h += words[i].size();
            if (i == 0) strStr(s, words[i], id);
            else if (words[i] != words[i - 1]) strStr(s, words[i], ++id);
            L[id] = words[i].size();
            ++n[id];
        }
        for (int i = 0; i + h - 1 < s.size(); ++i) {
            for (int k = 0; k <= id; ++k)
                AA[k] = n[k];
            if (_ok(i, words.size())) ans.push_back(i);
        }
        return ans;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值