码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Remove Duplicate Letters

时间:2015-12-26 23:33:11      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

 

 

 

 

[LeetCode][JavaScript]Remove Duplicate Letters

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/5079176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!