Simple 6ms Java solution with makeshift stack


  • 0
    Y
    public class Solution {
        public String removeDuplicateLetters(String s) {
            if (s == null || s.isEmpty()) return new String();
            boolean[] used = new boolean[26];
            int[] counts = new int[26];
            for (int i = 0; i < s.length(); i++) counts[s.charAt(i) - 'a']++;
            char[] stack = new char[s.length()];
            stack[0] = s.charAt(0);
            used[s.charAt(0) - 'a'] = true;
            counts[s.charAt(0) - 'a']--;
            int cur = 1;
            for (int i = 1; i < s.length(); i++) {
                counts[s.charAt(i) - 'a']--;
                if (used[s.charAt(i) - 'a']) continue;
                while (cur > 0 && s.charAt(i) < stack[cur - 1] && counts[stack[cur - 1] - 'a'] > 0) {
                    used[stack[cur - 1] - 'a'] = false;
                    cur--;
                }
                stack[cur++] = s.charAt(i);
                used[s.charAt(i) - 'a'] = true;
            }
            return String.valueOf(stack, 0, cur);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.