zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    【Java】组合 继承 代理
    《Thinking In Java》笔记之十三章 字符串
    常用Dos命令
    Thinking in Java异常笔记与习题
    php去重 逗号分隔的字符串
    php 连接本地数据库
    vue重载子组件
    小程序更改checked样式
    JavaScript中两个数组的拼接
    FROM_UNIXTIME()时间戳转换函数
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5079176.html
Copyright © 2011-2022 走看看