1358. Number of Substrings Containing All Three Characters

Given a string s consisting only of characters ab and c.

Return the number of substrings containing at least one occurrence of all these characters ab and c.

 

Example 1:

Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters ab 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 ab 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 ab or characters.

思路:two pointer

class Solution(object):
    def numberOfSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        n=len(s)
        i=j=0
        d={'a':0,'b':0,'c':0}
        res=0
        while j<n:
            d[s[j]] += 1
            j += 1
            while min(d.values())>0:
                res+=n-j+1
                d[s[i]] -= 1
                i+=1

        return res

s=Solution()
print(s.numberOfSubstrings("abcabc"))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章