forked from webVueBlog/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
去除重复字母.js
49 lines (47 loc) · 1019 Bytes
/
去除重复字母.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
/**
* @param {string} s
* @return {string}
316. 去除重复字母
cbabca
[c] b // [b]
[a,b,c]
"bcabc"
[b,c,a]
"cbacdcbc"
[a]
"ecbacba"
cbabc // cbab
i
[c] // abcdef
v = s[i] < stack.[stack.length-1]
如果当前字符比栈顶字符小,删除栈顶(i指针后面还有栈顶字符)
*/
var removeDuplicateLetters = function(s) {
let stack = [];
const countMap = {};
const exist = {};
const n = s.length;
for(let i = 0; i < n; i++) {
const v = s[i];
if(countMap[v] === undefined) {
countMap[v] = 0;
}
countMap[v]++;
}
for(let i = 0; i<n; i++) {
const v = s[i];
countMap[v]--;
if(exist[v]) {
continue;
}
while(stack.length && stack[stack.length-1] > v) {
if(countMap[stack[stack.length-1]] === 0) {
break;
}
exist[stack.pop()] = false
}
stack.push(v);
exist[v] = true;
}
return stack.join('');
};