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 1:

Input:
"bcabc"
Output:
"abc"

Example 2:

Input:
"cbacdcbc"
Output:
"acdb"
class Solution {
    public String removeDuplicateLetters(String s) {
        if (s == null || s.length() == 0) return s;

        int[] count = new int[26];
        for (char c : s.toCharArray()){
            count[c - 'a']++;
        }

        boolean[] visited = new boolean[26];
        Stack<Character> stack = new Stack<>();

        for (char c : s.toCharArray()){
            int pos = c - 'a';
            count[pos]--;

            if (visited[pos]) continue;

            while (!stack.isEmpty() && stack.peek() > c && count[stack.peek() - 'a'] > 0){
                visited[stack.pop() - 'a'] = false;
            }

            visited[pos] = true;
            stack.push(c);
        }

        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }

        return sb.reverse().toString();
    }
}

results for ""

    No results matching ""