LeetCode[316] Remove Duplicate Letters

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.app

Example:
Given "bcabc"
Return "abc"ui

Given "cbacdcbc"
Return "acdb"code

ascii array

複雜度
O(N), O(N)ci

思路
用一個stack,每次考慮當前的字符大小和stack的頂端字符的大小,若是當前字符比較小的話,則能夠poll出stack頂端的字符,將當前的字符放進stack中。須要維持了一個array判斷當前字符在剩餘字符串中的出現次數,考慮可否將這個字符從棧中彈出。rem

代碼字符串

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();
}
相關文章
相關標籤/搜索