Skip to content

Commit 90608da

Browse files
authored
Create longest-ab-substring.py
1 parent 353d22f commit 90608da

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

longest-ab-substring.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
"""
3+
@param S: a String consists of a and b
4+
@return: the longest of the longest string that meets the condition
5+
"""
6+
def getAns(self, S):
7+
# Write your code here
8+
r = 0
9+
diff = 0
10+
diffs = []
11+
pos = {}
12+
for i in range(len(S)):
13+
if S[i] == 'A':
14+
diff += 1
15+
else:
16+
diff -= 1
17+
diffs.append(diff)
18+
pos[diff] = i
19+
for i in range(len(S)):
20+
if diffs[i] != 0:
21+
if r <= pos[diffs[i]] - i:
22+
r = pos[diffs[i]] - i
23+
if 0 in pos:
24+
if (pos[0] + 1) > r:
25+
r = pos[0] + 1
26+
return r

0 commit comments

Comments
 (0)