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"

Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.

Solution

public class Solution {
  public String removeDuplicateLetters(String s) {
        if (s == null || s.length() <= 1) return s;

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

        Stack<Character> stack = new Stack<>();
        int index = 0;

        while (index < s.length()) {
            char currentChar = s.charAt(index);

            if (!stack.contains(currentChar)) {
                while (!stack.isEmpty() && dict[stack.peek() - 'a'] >= 1 && currentChar < stack.peek()) {
                    stack.pop();
                }

                stack.push(currentChar);
            }

            dict[currentChar - 'a'] -= 1;
            index++;
        }

        StringBuffer sb = new StringBuffer();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }

}

results matching ""

    No results matching ""