给你两个字符串 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)。