[LintCode/LeetCode] Remove Duplicate Letters

Problem

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"

Solution

public class Solution {
    /**
     * @param s: a string
     * @return: return a string
     */
    public String removeDuplicateLetters(String s) {
        // write your code here
        int[] count = new int[26]; // char-'a'
        char[] stack = new char[26]; // index
        boolean[] inStack = new boolean[26]; // char-'a'
        
        for (char ch: s.toCharArray()) count[ch-'a']++;
        
        int index = 0;
        for (char ch: s.toCharArray()) {
            count[ch-'a']--;
            if (!inStack[ch-'a']) {
                //check the stack: if has larger element
                while (index > 0 && stack[index-1] > ch && count[stack[index-1]-'a'] > 0) {
                    index--;
                    inStack[stack[index]-'a'] = false;
                }
                stack[index++] = ch;
                inStack[ch-'a'] = true;
            }
        }
        return new String(stack, 0, index);
    }
}
阅读 1.1k

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页