Remove All Adjacent Duplicates in String II
franklinqin0 StringStack
# Solution
Let be the string length.
# Brute Force (TLE)
Complexity
time: (scan s no more than times)
space:
def removeDuplicates(self, s: str, k: int) -> str:
n = -1
while n != len(s):
n = len(s)
count = 1
for i in range(n):
if i == 0 or s[i] != s[i-1]:
count = 1
else:
count += 1
if count == k:
s = s[:i-k+1] + s[i+1:]
break
return s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# HashMap
Complexity
time:
space:
def removeDuplicates(self, s: str, k: int) -> str:
i = 0
counts = [0 for _ in range(len(s))]
while i < len(s):
if i == 0 or s[i] != s[i-1]:
counts[i] = 1
else:
counts[i] = counts[i - 1] + 1
if counts[i] == k:
s = s[:i-k+1] + s[i+1:]
i -= k
i += 1
return s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Stack
Complexity
time:
space:
def removeDuplicates(self, s: str, k: int) -> str:
i = 0
counts = []
while i < len(s):
if i == 0 or s[i] != s[i-1]:
counts.append(1)
else:
counts[-1] += 1
if counts[-1] == k:
counts.pop()
s = s[:i-k+1] + s[i+1:]
i -= k
i += 1
return s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Two Pointers
Complexity
time:
space:
def removeDuplicates(self, s: str, k: int) -> str:
s = list(s)
j = 0
counts = []
for i in range(len(s)):
s[j] = s[i]
if j == 0 or s[j] != s[j - 1]:
counts.append(1)
else:
counts[-1] += 1
if counts[-1] == k:
counts.pop()
j -= k
j += 1
return "".join(s[:j])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16