-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathlongest-balanced-substring-i.py
More file actions
46 lines (41 loc) · 1.19 KB
/
longest-balanced-substring-i.py
File metadata and controls
46 lines (41 loc) · 1.19 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
46
# Time: O(n * (a + n))), a = len(set(s))
# Space: O(a)
import collections
# freq table
class Solution(object):
def longestBalanced(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for i in xrange(len(s)):
cnt = collections.defaultdict(int)
mx = 0
for j in xrange(i, len(s)):
cnt[s[j]] += 1
mx = max(mx, cnt[s[j]])
if (j-i+1)%len(cnt) == 0 and (j-i+1)//len(cnt) == mx:
result = max(result, j-i+1)
return result
# Time: O(n * (26 + n))
# Space: O(26)
# freq table
class Solution2(object):
def longestBalanced(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for i in xrange(len(s)):
cnt = [0]*26
mx = unique = 0
for j in xrange(i, len(s)):
if cnt[ord(s[j])-ord('a')] == 0:
unique += 1
cnt[ord(s[j])-ord('a')] += 1
mx = max(mx, cnt[ord(s[j])-ord('a')])
if (j-i+1)%unique == 0 and (j-i+1)//unique == mx:
result = max(result, j-i+1)
return result