51nod 1255 字典序最小的子序列

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1255&judgeId=499251

题意:出现过的字母都要输出一次,而且要字典序最小

从左到右一个一个字母判断:
如果没遇到过,就算上,但是如果这个字母比上一个要小,我们是不是考虑要把这个字母放到靠前一点我位置呢?
于是这个时候就分情况了,如果这个字母比上一个小,而上一个字母在后面还有,那么上一个字母就不要了,用后面的,于是当前字母就靠前了~

#include<stack>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1e5+5;
char s[maxn];
char ans[maxn];
int main()
{
    while(cin>>s)
    {
        bool vis[26];
        int a[26];
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
        int len=strlen(s);
        for(int i=0;i<len;i++)a[s[i]-'a']++;
        stack<char>st;
        for(int i=0;i<len;i++)
        {
            if(st.empty())
            {
                st.push(s[i]);
                vis[s[i]-'a']=1;
                a[s[i]-'a']--;///加入栈中用掉一个,所以减少一个
            }
            else if(vis[s[i]-'a'])
            {
                a[s[i]-'a']--;
                continue;
            }

            else if(vis[s[i]-'a']==0)
            {
                ///没在里面分两种情况:
                ///1.比栈顶小:如果栈顶的字母后面还有,就要剔除
                while(a[st.top()-'a']>=1&&s[i]<st.top())
                {
                    vis[st.top()-'a']=0;
                    st.pop();
                    if(st.empty())break;
                }
                st.push(s[i]);
                vis[s[i]-'a']=1;
                a[s[i]-'a']--;///加入栈中用掉一个,所以减少一个
            }
        }
        int t=0;
        while(!st.empty())
        {
            ans[t++]=st.top();
            st.pop();
        }
        reverse(ans,ans+t);
        ans[t]=0;
        cout<<ans<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值