-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy path0316_remove_duplicate_letters_(medium).js
More file actions
63 lines (54 loc) · 1.24 KB
/
Copy path0316_remove_duplicate_letters_(medium).js
File metadata and controls
63 lines (54 loc) · 1.24 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 316. Remove Duplicate Letters
*
* https://leetcode.com/problems/remove-duplicate-letters/
*
* Given a string which contains only lowercase letters, remove duplicate letters so that
* every letter appear once and only once. You must make sure your result is the smallest
* in lexicographical order among all possible results.
*
* Also make sure you keep the original order.
*
* Example 1:
*
* Input: "bcabc"
* Output: "abc"
*
* Example 2:
*
* Input: "cbacdcbc"
* Output: "acdb"
*/
Object.defineProperty(Array.prototype, 'last', {
get: function () {
return this[this.length - 1];
},
});
/**
* @param {string} s
* @return {string}
*/
const removeDuplicateLetters = (s) => {
// Step 1. Build a counter map and count the characters
const counter = {};
for (let c of s) {
counter[c] = ~~counter[c] + 1;
}
// Step 2. Go through the string
const result = [];
const visited = new Set();
for (let c of s) {
counter[c]--; // important
if (visited.has(c)) {
continue;
}
while (result.last > c && counter[result.last] > 0) {
visited.delete(result.last);
result.pop();
}
result.push(c);
visited.add(c);
}
return result.join('');
};
export { removeDuplicateLetters };