-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path125.py
More file actions
45 lines (35 loc) · 1.47 KB
/
125.py
File metadata and controls
45 lines (35 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution:
def numberOfSubstrings(self, s: str) -> int:
left = right = total = 0
# Track frequency of a, b, c
freq = [0] * 3
while right < len(s):
# Add character at right pointer to frequency array
freq[ord(s[right]) - ord("a")] += 1
# While we have all required characters
while self._has_all_chars(freq):
# All substrings from current window to end are valid
# Add count of valid substrings
print(f"{left}-{right}-{len(s) - right}")
total += len(s) - right
# Remove leftmost character and move left pointer
freq[ord(s[left]) - ord("a")] -= 1
left += 1
right += 1
return total
def _has_all_chars(self, freq: list) -> bool:
# Check if we have at least one of each character
return all(f > 0 for f in freq)
class Solution2:
def numberOfSubstrings(self, s: str) -> int:
# Track last position of a, b, c
last_pos = [-1] * 3
total = 0
for pos in range(len(s)):
# Update last position of current character
last_pos[ord(s[pos]) - ord("a")] = pos
# Add count of valid substrings ending at current position
# If any character is missing, min will be -1
# Else min gives leftmost required character position
total += 1 + min(last_pos)
return total