Skip to content

Commit 319710b

Browse files
committed
Add num of ways to split a string
1 parent 3d1d616 commit 319710b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: strings/num_splits.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
You are given a string s, a split is called good if you can split s into
3+
2 non-empty strings p and q where its concatenation is equal to s and
4+
the number of distinct letters in p and q are the same.
5+
6+
Return the number of good splits you can make in s.
7+
"""
8+
from collections import Counter, defaultdict
9+
10+
def num_splits(self, s: str):
11+
"""
12+
>> num_splits("aacaba")
13+
2
14+
>> num_splits("abcd")
15+
1
16+
>> num_splits("aaaaa")
17+
4
18+
"""
19+
ans = 0
20+
rightSplit = Counter(s)
21+
leftSplit = defaultdict(int)
22+
23+
leftCount = 0
24+
rightCount = len(rightSplit)
25+
26+
for ch in s:
27+
rightSplit[ch] -= 1
28+
leftSplit[ch] += 1
29+
30+
if rightSplit[ch] == 0:
31+
rightCount -= 1
32+
33+
leftCount = len(leftSplit)
34+
35+
if leftCount == rightCount:
36+
ans += 1
37+
38+
return ans
39+
40+
41+
if __name__ == "__main__":
42+
import doctest
43+
44+
doctest.testmod()

0 commit comments

Comments
 (0)