LeetCode 3298.统计重新排列后包含另一个字符串的子字符串数目2

给你两个字符串 word1 和 word2 。

如果一个字符串 x 重新排列后,word2 是重排字符串的 前缀 ,那么我们称字符串 x 是 合法的 。

请你返回 word1 中 合法 子字符串 的数目。

注意 ,这个问题中的内存限制比其他题目要 小 ,所以你 必须 实现一个线性复杂度的解法。

示例 1:

输入:word1 = “bcca”, word2 = “abc”

输出:1

解释:

唯一合法的子字符串是 “bcca” ,可以重新排列得到 “abcc” ,“abc” 是它的前缀。

示例 2:

输入:word1 = “abcabc”, word2 = “abc”

输出:10

解释:

除了长度为 1 和 2 的所有子字符串都是合法的。

示例 3:

输入:word1 = “abcabc”, word2 = “aaabc”

输出:0

解释:

1 <= word1.length <= 10 6 ^6 6
1 <= word2.length <= 10 4 ^4 4
word1 和 word2 都只包含小写英文字母。

滑动窗口,当窗口内的字符符合题意时,加上窗口左边的字符也符合题意:

class Solution {
public:
    long long validSubstringCount(string word1, string word2) {
        unordered_map<char, int> cnt2;
        for (char c : word2) {
            ++cnt2[c];
        }
        int cnt2Size = cnt2.size();

        long long ans = 0;
        unordered_map<char, int> curCnt;
        int left = 0;
        int more = 0;
        for (int i = 0; i < word1.size(); ++i) {
            if (++curCnt[word1[i]] == cnt2[word1[i]]) {
                ++more;
            }

            while (more == cnt2Size) {
                if (curCnt[word1[left]]-- == cnt2[word1[left]]) {
                    --more;
                }

                ++left;
            }

            ans += left;
        }

        return ans;
    }
};

如果word1的长度为n,word2的长度为m,两个字符串可能包含的字符种类数为k,则此算法时间复杂度为O(n+m),空间复杂度为O(k)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值