LeetCode 1358.包含所有三种字符的子字符串数目
给你一个字符串 s ,它只包含三种字符 a, b 和 c 。
请你返回 a,b 和 c 都 至少 出现过一次的子字符串数目。
示例 1:
输入:s = “abcabc”
输出:10
解释:包含 a,b 和 c 各至少一次的子字符串为 “abc”, “abca”, “abcab”, “abcabc”, “bca”, “bcab”, “bcabc”, “cab”, “cabc” 和 “abc” (相同字符串算多次)。
示例 2:
输入:s = “aaacb”
输出:3
解释:包含 a,b 和 c 各至少一次的子字符串为 “aaacb”, “aacb” 和 “acb” 。
示例 3:
输入:s = “abc”
输出:1
提示:
3 <= s.length <= 5 x 10^4
s 只包含字符 a,b 和 c 。
滑动窗口,当窗口内的子串包含所有三种字符时,包含其左边字符的子串也同样满足需求:
class Solution {
public:int numberOfSubstrings(string s) {int ans = 0;int left = 0;unordered_map<char, int> cnt;int enough = 0;for (int i = 0; i < s.size(); ++i) {if (++cnt[s[i]] == 1) {++enough;}while (enough == 3) {if (--cnt[s[left]] == 0) {--enough;}++left;}ans += left;}return ans;}
};
如果输入字符串的长度为n,字符种类为m,则此算法时间复杂度为O(n),空间复杂度为O(m)。