-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-all-adjacent-duplicates-in-string.js
75 lines (61 loc) · 1.85 KB
/
remove-all-adjacent-duplicates-in-string.js
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
/**
* Remove All Adjacent Duplicates In String
*
* Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
*
* We repeatedly make duplicate removals on S until we no longer can.
*
* Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
*
* Example 1:
*
* Input: "abbaca"
* Output: "ca"
* Explanation:
* For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
*/
/**
* @param {string} S
* @return {string}
* @time complexity: O(n) where n is the length of S
* @space complexity: O(n)
*/
var removeDuplicates = function(S) {
const stack = [];
for (let c of S) {
if (c !== stack[stack.length - 1]) {
stack.push(c);
} else {
stack.pop();
}
}
return stack.join('');
};
/**
* @param {string} S
* @return {string}
* @time complexity: O(n) where n is the length of S
* @space complexity: O(n)
*/
var removeDuplicatesAlternative = function(S) {
const arr = S.split('');
for (let i = 1; i < arr.length; i++) {
if (arr[i] === arr[i-1]) {
arr.splice(i-1, 2);
i -= 2;
}
}
return arr.join('');
};
const assert = require('chai').assert;
describe('Remove All Adjacent Duplicates In String', () => {
it('should return \'ca\' when \'abbaca\' is given', () => {
assert.strictEqual(removeDuplicates('abbaca'), 'ca');
});
it('should return \'\' when \'aabbacca\' is given', () => {
assert.strictEqual(removeDuplicates('aabbacca'), '');
});
it('should return \'\' when \'\' is given', () => {
assert.strictEqual(removeDuplicates(''), '');
});
});