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 }
  • 相关阅读:
    关于开发BugRaid的想法(2)
    杭州.net俱乐部第一次见面会情况
    关于Bug管理的过程
    关于开发BugRaid的想法(1)
    变态的VS2005 SP1
    vs2003 sp1 download url
    proxy software
    敏捷开发
    Enterprise Library文档
    ETL
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5684495.html
Copyright © 2011-2022 走看看