Remove Duplicate Letters

题目地址:
https://leetcode.com/problems/remove-duplicate-letters/description/

题目:
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"
解题思路:
这道题可以用stack来做。

代码:


public String removeDuplicateLetters(String s) {
    int[] counts = new int[26];
    boolean[] visitedBefore = new boolean[26];
    char[] chars = s.toCharArray();

    // update the counts array    
    for(int i = 0; i < chars.length; i++){
        counts[chars[i] - 'a']++;
    }

    Stack<Character> stack = new Stack<>();

    int index = 0;
    for(char c : chars){
        index = c - 'a';
        counts[index]--;
        if(visitedBefore[index]){
            continue;
        }
        while(!stack.isEmpty() && stack.peek() > c && counts[stack.peek() - 'a'] != 0){
            visitedBefore[stack.pop() - 'a'] = false;
        }
        stack.push(c);
        visitedBefore[index] = true;
    }

    StringBuilder sb = new StringBuilder();
    while(!stack.isEmpty()){
        sb.insert(0, stack.pop());
    }
    return sb.toString();
}


Comments

Popular Posts