单调栈--最小字典序

1081. Smallest Subsequence of Distinct Characters

Medium

15628FavoriteShare

Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once.

 

Example 1:

Input: "cdadabcc"
Output: "adbc"

Example 2:

Input: "abcd"
Output: "abcd"

Example 3:

Input: "ecbacba"
Output: "eacb"

Example 4:

Input: "leetcode"
Output: "letcod"

 

Note:

  1. 1 <= text.length <= 1000
  2. text consists of lowercase English letters.
string smallestSubsequence(string text){
    stack<char> s;
    unordered_map<char,int> Map;
    unordered_set<char> Visited;
    string Result;
    for(int i = 0;i < text.length();i++){
        Map[text[i]] ++;
    }
    for(int i = 0;i < text.length();i ++){
        Map[text[i]] --;
        if(Visited.find(text[i]) != Visited.end()){
            continue;
        }
        while(!s.empty() && text[i] < s.top() && Map[s.top()] > 0){//--case : 1    要保证字符串中所有字符都包含在结果里,必须加入条件Map[s.top()]>0
                                                                   //--case : 2    如果不用保证最后的结果必须包含所有字符,就把这个条件删掉
            Visited.erase(s.top());
            s.pop();
        }
        s.push(text[i]);
        Visited.insert(text[i]);
    }
    while(!s.empty()){
        Result += s.top();
        s.pop();
    }
    reverse(Result.begin(),Result.end());
    return Result;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值