Skip to content

Commit efe2d9e

Browse files
authored
Create number-of-substrings-containing-all-three-characters.py
1 parent bd68c37 commit efe2d9e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def numberOfSubstrings(self, s):
6+
"""
7+
:type s: str
8+
:rtype: int
9+
"""
10+
result, left = 0, [-1]*3
11+
for right, c in enumerate(s):
12+
left[ord(c)-ord('a')] = right
13+
result += min(left)+1
14+
return result
15+
16+
17+
# Time: O(n)
18+
# Space: O(1)
19+
class Solution2(object):
20+
def numberOfSubstrings(self, s):
21+
"""
22+
:type s: str
23+
:rtype: int
24+
"""
25+
result, left, count = 0, 0, [0]*3
26+
for right, c in enumerate(s):
27+
count[ord(s[right])-ord('a')] += 1
28+
while all(count):
29+
count[ord(s[left])-ord('a')] -= 1
30+
left += 1
31+
result += left
32+
return result
33+
34+
35+
# Time: O(n)
36+
# Space: O(1)
37+
class Solution3(object):
38+
def numberOfSubstrings(self, s):
39+
"""
40+
:type s: str
41+
:rtype: int
42+
"""
43+
result, right, count = 0, 0, [0]*3
44+
for left, c in enumerate(s):
45+
while right < len(s) and not all(count):
46+
count[ord(s[right])-ord('a')] += 1
47+
right += 1
48+
if all(count):
49+
result += (len(s)-1) - (right-1) + 1
50+
count[ord(c)-ord('a')] -= 1
51+
return result

0 commit comments

Comments
 (0)