Skip to content

Remove duplicate letters

Tim_Gao edited this page Sep 16, 2016 · 1 revision
  1. time complexity: O(n)
public class Solution {
    public String removeDuplicateLetters(String s) {
        if (s.length() <2){
            return s;
        }
        Stack<Character> st = new Stack<>();
        HashMap<Character, Integer> hm = new HashMap<>();
        for (char ch : s.toCharArray()){
            if (!hm.containsKey(ch)){
                hm.put(ch, 0);
            }
            hm.put(ch, hm.get(ch)+1);
        }
        HashSet<Character> hs = new HashSet<>();
        for (int i=0; i<s.length(); ++i){
            hm.put(s.charAt(i), hm.get(s.charAt(i))-1);
            if (hs.contains(s.charAt(i))){
                continue;
            }
            while(!st.isEmpty() && s.charAt(i) < st.peek() && hm.get(st.peek()) > 0){
                hs.remove(st.pop());
            }
            st.push(s.charAt(i));
            hs.add(s.charAt(i));
        }
        StringBuilder sb = new StringBuilder();
        while(!st.isEmpty()){
            sb.append(st.pop());
        }
        return sb.reverse().toString();
    }
}

Clone this wiki locally