|
| 1 | +class Solution(object): |
| 2 | + def numberOfSubstrings(self, s): |
| 3 | + count = [0] * 3 # To store counts of 'a', 'b', and 'c' |
| 4 | + left = 0 # Left pointer of the window |
| 5 | + result = 0 # To store the result |
| 6 | + |
| 7 | + for i in range(len(s)): |
| 8 | + count[ord(s[i]) - ord('a')] += 1 # Increment the count of the current character |
| 9 | + |
| 10 | + # When all three characters are present in the window |
| 11 | + while count[0] > 0 and count[1] > 0 and count[2] > 0: |
| 12 | + result += len(s) - i # All substrings starting at left and ending at i or beyond are valid |
| 13 | + count[ord(s[left]) - ord('a')] -= 1 # Decrement the count of the left character |
| 14 | + left += 1 # Move the left pointer |
| 15 | + |
| 16 | + return result |
0 commit comments