LeetCode[316] 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"

ascii array

复杂度
O(N), O(N)

思路
用一个stack,每次考虑当前的字符大小和stack的顶端字符的大小,如果当前字符比较小的话,则可以poll出stack顶端的字符,将当前的字符放进stack中。需要维持了一个array判断当前字符在剩余字符串中的出现次数,考虑能否将这个字符从栈中弹出。

代码

public String removeDuplicateLetters(String s) {
    Stack<Character> stack = new Stack<>();
    int[] arr = new int[26];
    boolean[] visited = new boolean[26];
    for(int i = 0; i < s.length(); i ++) {
        arr[s.charAt(i) - 'a'] ++;
    }
    //
    for(int i = 0; i < s.length(); i ++) {
        char ch = s.charAt(i);
        arr[ch - 'a'] --;
        if(visited[ch - 'a']) continue;
        if(!stack.isEmpty() && ch < stack.peek()) {
            //
            while(!stack.isEmpty() && arr[stack.peek() - 'a'] > 0 && ch < stack.peek()) {
                char temp = stack.pop();
                visited[temp - 'a'] --;
            }
        }
        visited[ch - 'a'] = true;
        stack.push(ch);
    }
    // build the string;
    StringBuilder builder = new StringBuilder();
    while(!stack.isEmpty()) {
        builder.append(stack.pop());
    }
    return builder.reverse().toString();
}

hellolittleJ17
10 声望11 粉丝