-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathsmallest-substring-with-identical-characters-i.py
70 lines (62 loc) · 1.88 KB
/
smallest-substring-with-identical-characters-i.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Time: O(nlogn)
# Space: O(1)
# binary search, greedy
class Solution(object):
def minLength(self, s, numOps):
"""
:type s: str
:type numOps: int
:rtype: int
"""
def binary_search(left, right, check):
while left <= right:
mid = left + (right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
def lengths():
cnt = 0
for i in xrange(len(s)):
cnt += 1
if i+1 == len(s) or s[i+1] != s[i]:
yield cnt
cnt = 0
def check(x):
if x == 1:
cnt = sum(int(x) != i%2 for i, x in enumerate(s))
return min(cnt, len(s)-cnt) <= numOps
return sum(l//(x+1) for l in lengths()) <= numOps
return binary_search(1, len(s), check)
# Time: O(nlogn)
# Space: O(n)
# binary search, greedy
class Solution2(object):
def minLength(self, s, numOps):
"""
:type s: str
:type numOps: int
:rtype: int
"""
def binary_search(left, right, check):
while left <= right:
mid = left + (right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
def check(x):
if x == 1:
cnt = sum(int(x) != i%2 for i, x in enumerate(s))
return min(cnt, len(s)-cnt) <= numOps
return sum(l//(x+1) for l in arr) <= numOps
arr = []
cnt = 0
for i in xrange(len(s)):
cnt += 1
if i+1 == len(s) or s[i+1] != s[i]:
arr.append(cnt)
cnt = 0
return binary_search(1, len(s), check)