Description
Given a string s consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb"
Output: 3
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc"
Output: 1
Constraints:
- 3 <= s.length <= 5 x 10^4
- s only consists of a, b or c characters.
分析
题目的意思是:统计字符串子串中包含所有三个字符的子串的个数。这道题要找规律,不然很难写出来,可以用一个字典来统计当前遍历的每个字符的个数,当三个字符都出现的时候,我们就可以找到n-j组子数组包含该字符串,j为当前遍历的索引。这样可以加入结果集合中,继续遍历。比如:abcabc,当遍历到abc时,我们能够找到abc,abca,abcab,abcabc=n-j=4,哈哈哈,这个规律好难找。
代码
class Solution:
def numberOfSubstrings(self, s: str) -> int:
d=collections.defaultdict(int)
n=len(s)
i=0
res=0
for j,ch in enumerate(s):
d[ch]+=1
while(d['a'] and d['b'] and d['c']):
res+=n-j
d[s[i]]-=1
i+=1
return res
参考文献
[LeetCode] leetcode
1358. Number of Substrings Containing All Three Characters