forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-substrings-containing-all-three-characters.py
51 lines (46 loc) · 1.24 KB
/
number-of-substrings-containing-all-three-characters.py
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
46
47
48
49
50
51
# Time: O(n)
# Space: O(1)
class Solution(object):
def numberOfSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
result, left = 0, [-1]*3
for right, c in enumerate(s):
left[ord(c)-ord('a')] = right
result += min(left)+1
return result
# Time: O(n)
# Space: O(1)
class Solution2(object):
def numberOfSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
result, left, count = 0, 0, [0]*3
for right, c in enumerate(s):
count[ord(s[right])-ord('a')] += 1
while all(count):
count[ord(s[left])-ord('a')] -= 1
left += 1
result += left
return result
# Time: O(n)
# Space: O(1)
class Solution3(object):
def numberOfSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
result, right, count = 0, 0, [0]*3
for left, c in enumerate(s):
while right < len(s) and not all(count):
count[ord(s[right])-ord('a')] += 1
right += 1
if all(count):
result += (len(s)-1) - (right-1) + 1
count[ord(c)-ord('a')] -= 1
return result