首页 > 其他分享 >单调栈--最小字典序

单调栈--最小字典序

时间:2022-10-26 20:42:22浏览次数:36  
标签:Map -- text top Result Input Visited 单调 字典


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;
}

 

标签:Map,--,text,top,Result,Input,Visited,单调,字典
From: https://blog.51cto.com/u_13121994/5798362

相关文章

  • 将以逗号为分隔符的数字提取出来的模板
    #include<iostream>#include<vector>#include<string>usingnamespacestd;strings;vector<int>Input;intmain(){cin>>s;for(inti=0;i<s.size();i++)......
  • 新浪微博2020界校招笔试-算法工程师
        给定字符串A,A是由逗号分割的数字串,A可以解析成整数数组B。每次操作可以选择任意B[i],并将其递增1.返回使得B中的每个值都是唯一的最小操作次数。输入描述:输入每......
  • 单调栈--HDOJ4252A Famous City
    ProblemDescriptionAfterMr.BarrivedinWarsaw,hewasshockedbytheskyscrapersandtookseveralphotos.Butnowwhenhelooksatthesephotos,hefindsin......
  • 单调栈--Largest Rectangle in a Histogram
    DescriptionAhistogramisapolygoncomposedofasequenceofrectanglesalignedatacommonbaseline.Therectangleshaveequalwidthsbutmayhavedifferent......
  • 单调栈--Feel Good
    DescriptionBillisdevelopinganewmathematicaltheoryforhumanemotions.Hisrecentinvestigationsarededicatedtostudyinghowgoodorbaddaysinfluentpe......
  • 并查集--翻译机的个数(顺丰2020年笔试)
    某学术会议上,一共有n个人参加,现在已知每个人会的语言(一个人可能不会任何语言)。现在有一种学习机,每一个学习机可以在会议期间使一个人暂时掌握一种自己不会的语言,问要使得任......
  • 最长非递减子序列--顺丰2020校招笔试题
    n的范围是[0,100000]DP版本(O(n^2))时间复杂度(LTE):#include<cstdio>#include<iostream>#include<algorithm>usingnamespacestd;#defineN100intmain(){intA[N],dp[N......
  • 字符串--移除k个数使得剩下的数最大
    有一十进制正整数,移除其中的K个数,使剩下的数字是所有可能中最大的。假设:字符串的长度一定大于等于K字符串不会以0开头 输入描述:一行由正整数组成的数字字符串,和......
  • DP--爬楼梯1
    题目描述前几个月放映的头号玩家简直火得不能再火了,作为一个探索终极AI的研究人员,月神自然去看了此神剧。由于太过兴奋,晚上月神做了一个奇怪的梦,月神梦见自己掉入了一个被施......
  • DP--字符串变换
    给定两个字符串,已知可以使用三种方式进行变换1.插入一个字符2.删除一个字符3.更改一个字符请设计一个算法,找到两个字符串之间的经历几次最小变换,可以字符串1转换成字......