-
Notifications
You must be signed in to change notification settings - Fork 1
/
1209. Remove All Adjacent Duplicates in String II.java
97 lines (81 loc) · 1.98 KB
/
1209. Remove All Adjacent Duplicates in String II.java
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//brute force approach - O(n^2)
class Solution {
public String removeDuplicates(String s, int k) {
StringBuilder str = new StringBuilder(s);
int len = -1;
while(len!=str.length())
{
len = str.length();
int c=1;
for(int i=0;i<str.length();i++)
{
if(i==0 || str.charAt(i-1)!=str.charAt(i))
{
c=1;
}
else
{
c++;
}
if(c == k)
{
str.delete(i-k+1,i+1);
break;
}
}
}
return str.toString();
}
}
//OPTIMAL SOLUTION - O(n)
class Solution {
public String removeDuplicates(String s, int k) {
StringBuilder str = new StringBuilder(s);
int count [] = new int[str.length()];
for(int i=0;i<str.length();i++)
{
if(i==0 || str.charAt(i-1)!=str.charAt(i))
{
count[i] = 1;
}
else
{
count[i] = count [i-1] + 1;
if(count [i] == k)
{
str.delete(i-k+1,i+1);
i=i-k;
}
}
}
return str.toString();
}
}
//OPTIMAL SOLUTION - using stacks - O(n)
class Solution {
public String removeDuplicates(String s, int k) {
StringBuilder str = new StringBuilder(s);
Stack<Integer> count =new Stack<Integer>();
for(int i=0;i<str.length();i++)
{
if(i==0 || str.charAt(i-1)!=str.charAt(i))
{
count.push(1);
}
else
{
int temp = count.pop() +1 ;
if(temp == k)
{
str.delete(i-k+1,i+1);
i=i-k;
}
else
{
count.push(temp);
}
}
}
return str.toString();
}
}