• [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 };
  • 相关阅读:
    让DateTimePicker显示空时间值 (转) 武胜
    Webcam in C#: AForge.NET (转) 武胜
    C#自定义事件的步骤 武胜
    交换机VLAN的配置 (转) 武胜
    虚拟LAN安全的最佳实践经验 (转) 武胜
    绿色版 MySQL 的安装配置 (转) 武胜
    net 中捕获摄像头视频的方式及对比(How to Capture Camera Video via .Net) (转) 武胜
    C# WndProc的使用方法 (转) 武胜
    金融证券业Windows NT服务器热备份系统工作示意图 (转) 武胜
    ubuntu下配置samba实现文件夹共享
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5079176.html
Copyright © 2020-2023  润新知