zoukankan      html  css  js  c++  java
  • LeetCode-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"

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.

    Analysis:

    We maintain a smallest valid char list and iterate through the whole string. When we move to the next char, we want to put it as ahead as possible in the valid char list so we want to remove all chars that are larger than it straing from the tail, e.g., "acd" and the next char is 'b', we then want to put it after 'a'; however, whether we can remove 'd' and 'c' depends on whether there are still 'b' and 'c' in the left string, if yes, then we can safely remove them.

    Also, if we cannot remove 'd', then we cannot remove any chars in front of 'd', because this will actually enlarge the lexicographical order. e.g., "acd" and the following is "bc", if we remove "c", then the result is "adbc" which is larger than "acdb".

    Solution:

     1 public class Solution {
     2     public String removeDuplicateLetters(String s) {
     3         if (s.length() == 0)
     4             return s;
     5 
     6         int[] charCount = new int[26];
     7         boolean[] inStack = new boolean[26];
     8         Arrays.fill(charCount, 0);
     9         Arrays.fill(inStack, false);
    10         char[] charArray = s.toCharArray();
    11         for (char c : charArray) {
    12             charCount[c - 'a']++;
    13         }
    14 
    15         Stack<Character> resStack = new Stack<Character>();
    16         for (char c : charArray) {
    17             int index = c - 'a';
    18             charCount[index]--;
    19             
    20             if (inStack[index])
    21                 continue;
    22 
    23             while (!resStack.isEmpty() && resStack.peek() > c && charCount[resStack.peek() - 'a'] > 0) {
    24                 inStack[resStack.pop() - 'a'] = false;
    25             }
    26 
    27             resStack.push(c);
    28             inStack[index] = true;
    29         }
    30 
    31         StringBuilder builder = new StringBuilder();
    32         while (!resStack.isEmpty()) {
    33             builder.append(resStack.pop());
    34         }
    35         return builder.reverse().toString();
    36     }
    37 }
  • 相关阅读:
    linux命令(14):ifup/ifdown/ip addr命令
    linux命令(13):kill/killall命令
    linux命令(12):ping命令
    linux命令(11):df命令
    linux命令(9):route命令
    npm安装node-sass报msbuild相关错误的解决办法
    'vue-cli-service' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
    redis发布与订阅的实现
    设计模式-工厂模式
    设计模式的介绍
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5684495.html
Copyright © 2011-2022 走看看