[leetcode] 1358. Number of Substrings Containing All Three Characters

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值