LeetCode |すべての三文字を含むサブストリングの1358数は、3つのすべての文字[パイソン]のサブ文字列の数を含めます

すべての三文字を含むサブストリングのLeetCode 1358数は、サブストリング、3つすべてのPython [中] [] [] [デュアルスライディングウィンドウポインタ]の文字数が含まれています

問題

LeetCode

文字列与えられたs文字だけからなるBおよびCを

含むサブストリングの数戻り少なくともすべてのこれらの文字のいずれかの発生B及びCを

例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). 

例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". 

例3:

Input: s = "abc"
Output: 1

制約:

  • 3 <= s.length <= 5 x 10^4
  • sのみで構成されBまたはCの文字。

問題

電源ボタン

あなたの文字列を与えs、それが唯一の3つの文字、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が含まれています。

思考

デュアルポインタ スライディングウィンドウ

1. 如果窗口内有 a, b, c, 那么窗口继续向右拉开都满足
2. 如果窗口内没有 a, b, c, 那么 right 指针右移找到满足窗口内有 a,  b, c
3. 然后 left 指针右移,每次都要判断上面两种情况

時間複雑: O(N-)
スペースの複雑さ: O(N-)

python3コード

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        if len(s) <= 2:
            return 0
        length = len(s)
        left, right = 0, 2
        ans = 0
        while left < length - 2:
            window = s[left: right + 1]  # [left, right + 1)
            if 'a' in window and 'b' in window and 'c' in window:
                ans += length - right  # if s[left: right + 1] satisfies, then s[left: length] also satisfies
                left += 1  # move left
            else:
                right += 1  # move right
                if right == length:  # s[left: length] does not satisfy, so s[left + x: length] also does not satisfy
                    break
        return ans

コードアドレス

GitHubのリンク

おすすめ

転載: www.cnblogs.com/wonz/p/12348678.html