美文网首页程序员
力扣 316 去除重复字母

力扣 316 去除重复字母

作者: zhaojinhui | 来源:发表于2020-11-25 02:51 被阅读0次

    题意:给定一个字符串,返回去除重复后,安字典顺序最大的字符串

    思路:具体见代码注释

    思想:双向队列

    复杂度:时间O(n),空间O(n)

    class Solution {
        public String removeDuplicateLetters(String s) {
            
            //store the last index for each letter
            int[] arr = new int[26];
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                arr[c-'a'] = i;
            }
            
            //keep track if letter has been added
            HashSet<Character> set = new HashSet<>();
            Deque<Character> stack = new ArrayDeque<>();
            
            for(int i = 0; i< s.length(); i++) {
                char c = s.charAt(i);
                
                //always add letter if not yet added
                if(!set.contains(c)) {
                
                   //keep removing if previous letter is bigger and the letter is available later   
                    while(!stack.isEmpty() && (stack.peek() > c) && (arr[stack.peek()-'a'] > i)) {
                        char tmp = stack.pop();
                        set.remove(tmp);
                    }
                    set.add(c);
                    stack.push(c);
                }
            }
            
            //append and reverse before return
            StringBuilder sb = new StringBuilder();
            while(!stack.isEmpty()) {
                sb.append(stack.pop());
            }
            return sb.reverse().toString();
        }
    }
    

    相关文章

      网友评论

        本文标题:力扣 316 去除重复字母

        本文链接:https://www.haomeiwen.com/subject/gqcsiktx.html