316. Remove Duplicate Letters

29 篇文章 0 订阅
2 篇文章 0 订阅

316. Remove Duplicate Letters

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

 

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of lowercase English letters.

解题思路:此题使用statck保存不重复的字符串,在遍历主串时使用visited检查是否栈中已经有字符串,如果已经压入栈则继续遍历,为了保证压入栈中的字符串为最小字典序,每次入栈的时候和栈顶进行比对,如果小于栈顶则要考虑要不要把栈顶pop,依据的是m_count中记录的字符个数,如果m_count中对应字符大于0,则后面还有字符可以pop,否则压栈。代码如下:

class Solution {
public:
    string removeDuplicateLetters(string s) {
        if(s.size() < 2)
            return s;
        
        stack<char> st;
        unordered_map<char, bool>visited;
        unordered_map<char, int>m_count;
        for(auto c:s)
        {
            m_count[c]++;
        }
        
        for(int i = 0; i < s.size(); i++)
        {
            if(visited[s[i]])
            {
                m_count[s[i]]--;
                continue;
            }
                
            while(!st.empty() && s[i] < st.top() && m_count[st.top()] > 0)
            {
                visited[st.top()] = false;
                st.pop();
            }
            
            st.push(s[i]);
            visited[s[i]] =true;
            m_count[s[i]]--;
        }
        
        string str = "";
        
        while(!st.empty())
        {
            str = st.top() + str;
            st.pop();
        }
        
        return str;
    }
};

单调栈去重

[LeetCode] Remove Duplicate Letters 移除重复字母

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值