[LeetCode][JavaScript]Remove Duplicate Letters

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.

Example:

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"

https://leetcode.com/problems/maximum-product-of-word-lengths/

 

 


 

 

题意是移除重复的字母,留下的字母,字母序要最小。

第一种解法,贪心,复杂度O(n^2)。

每一轮统计字母出现的次数,从左往右找最小的或者只出现一次的字母,如果最小的字母有多个,取最左的那个。

 

 1 /**
 2  * @param {string} s
 3  * @return {string}
 4  */
 5 var removeDuplicateLetters2 = function(s) {
 6     var res = "", i, pos, countCh = {}, charCodeA = 'a'.charCodeAt(0);
 7     while(s !== ""){
 8         for(i = 0; i < 26; i++) countCh[String.fromCharCode(i + charCodeA)] = 0;
 9         for(i = 0; i < s.length; i++) countCh[s[i]]++;
10         pos = 0;
11         for(i = 0; i < s.length; i++){
12             if(s[i] < s[pos]) pos = i;
13             if(countCh[s[i]] === 1) break;
14             countCh[s[i]]--;
15         }
16         res += s[pos];
17         s = s.substring(pos + 1, s.length).replace(new RegExp(s[pos], 'g'), '');
18     }
19     return res;    
20 };

 

 

第二种解法多用了一个栈,复杂度复杂度O(n)。

维护的栈最后就是结果,一开始还是要统计所有字母出现的次数。

往数组里放字母是个贪心的过程,每轮循环,如果这个字母不在栈中,当前元素入栈。

但在之前要检查栈里的字母,如果栈顶字母比当前字母大而且栈顶元素之后还会出现,那么要出栈,因为放在后面的话字母序比较小,比如bab中的第二个b。

 

 1 /**
 2  * @param {string}
 3  * @return {string}
 4  */
 5 var removeDuplicateLetters = function(s) {
 6     var i, countCh = {}, charCodeA = 'a'.charCodeAt(0), stack = [], visited = {}, top;
 7     for(i = 0; i < 26; i++) countCh[String.fromCharCode(i + charCodeA)] = 0;
 8     for(i = 0; i < s.length; i++) countCh[s[i]]++;
 9     for(i = 0; i < s.length; i++){
10         countCh[s[i]]--;
11         if(visited[s[i]]) continue;
12         top = stack[stack.length - 1];
13         for(; stack.length > 0 && countCh[top] > 0 && s[i] < top; top = stack[stack.length - 1]){
14             visited[top] = false;
15             stack.pop();
16         }
17         stack.push(s[i]);
18         visited[s[i]] = true;
19     }
20     return stack.join('');    
21 };

 

 

 

 

 

转载于:https://www.cnblogs.com/Liok3187/p/5079176.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值