-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-deletions-to-make-alternating-substring.py
More file actions
47 lines (42 loc) · 1.26 KB
/
minimum-deletions-to-make-alternating-substring.py
File metadata and controls
47 lines (42 loc) · 1.26 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
47
# Time: O((n + q) * logn)
# Space: O(n)
# fenwick tree
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = 0
while i > 0:
ret += self.__bit[i]
i -= (i & -i)
return ret
class Solution(object):
def minDeletions(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[int]
"""
s = list(s)
bit = BIT(len(s)-1)
for i in xrange(len(s)-1):
if s[i] == s[i+1]:
bit.add(i, 1)
result = []
for q in queries:
if len(q) == 3:
result.append(bit.query(q[2]-1)-bit.query(q[1]-1))
continue
i = q[1]
s[i] = u'B' if s[i] == u'A' else u'A'
if i-1 >= 0:
bit.add(i-1, 1 if s[i-1] == s[i] else -1)
if i+1 < len(s):
bit.add(i, 1 if s[i] == s[i+1] else -1)
return result