leetcode 1047 - Remove All Adjacent Duplicates In String

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

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
class Solution {
public:
string removeDuplicates(string S) {
int end = S.size() - 1;
int new_end;

while (1) {
new_end = remove(S, end);
if (new_end == end)
break;
end = new_end;
}

return S.substr(0, new_end+1);
}

int remove(string &S, int end) {
char cur = S[0];
int i = 0;
int j = 0;

while (i <= end) {
int count = 0;
while (i <= end && S[i] == cur) {
i++;
count++;
}

if (count % 2)
S[j++] = cur;

if (i <= end)
cur = S[i];
}

return j - 1;
}
};