美文网首页程序员
力扣 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 去除重复字母

    题意:给定一个字符串,返回去除重复后,安字典顺序最大的字符串 思路:具体见代码注释 思想:双向队列 复杂度:时间O...

  • 一道数组去重的算法题把东哥整不会了

    读完本文,你可以去力扣拿下如下题目: 316.去除重复字母[https://leetcode-cn.com/pro...

  • 316. 去除重复字母

    316. 去除重复字母[https://leetcode-cn.com/problems/remove-dupli...

  • 单调栈

    316.去除重复字母(https://leetcode-cn.com/problems/remove-duplic...

  • 316. 去除重复字母

    题目 316. 去除重复字母 给定一个仅包含小写字母的字符串,去除字符串中重复的字母,使得每个字母只出现一次。需保...

  • 去除重复字母(LeetCode-316)

    LeetCode-316给你一个仅包含小写字母的字符串,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证...

  • LeetCode316. 去除重复字母

    1.题目描述 给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最...

  • leetcode-0316[更新打印宏及CMakeLists.t

    题目: 316. 去除重复字母 关键词: 单调栈,哈希表。 思路: 入栈条件:未入栈,且出现次数为1;统计出现次数...

  • LeetCode-python 316.去除重复字母

    题目链接难度:困难 类型: 贪心、栈 给定一个仅包含小写字母的字符串,去除字符串中重复的字母,...

  • 去除重复字母

    题目:去除重复字母(LeetCode-困难)给你一个仅包含小写字母的字符串,请你去除字符串中重复的字母,使得每个字...

网友评论

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

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