字典序最小的子序列

给出一个由a-z组成的字符串S,求他的一个子序列,满足如下条件:

1、包含字符串中所有出现过的字符各1个。
2、是所有满足条件1的串中,字典序最小的。

例如:babbdcc,出现过的字符为:abcd,而包含abcd的所有子序列中,字典序最小的为abdc。
Input
输入1行字符串S,所有字符均为小写,字符串的长度为L。(1 <= L <= 100000)。
Output
输出包含S中所有出现过的字符,每个字符各1个,并且字典序最小的S的子序列。
Input示例
babbdcc
Output示例
abdc

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;

char input[100001];
int count[26];

int main()
{
    cin >> input;
    int n = strlen(input);
	memset(count, 0, sizeof(count));

	for (int i = 0; i < n; i++)
	{
		count[input[i]-'a']++;
	}
	bool flag[26];
	memset(flag, false, sizeof(flag));

	stack<int> buf;

	for (int i = 0; i < n; i++)
	{
		count[input[i]-'a']--;
		if (flag[input[i]-'a'])
		{
			continue;
		}

        while (!buf.empty())
        {
            if (buf.top() > input[i] && count[buf.top()-'a'] > 0)
            {
                flag[buf.top()-'a'] = false;
                buf.pop();
            }
            else
            {
                break;
            }
        }
		
		buf.push(input[i]);
		flag[input[i]-'a'] = true;
	}

	int len = 0;
	while (!buf.empty())
	{
		input[len] = buf.top();
		len++;
		buf.pop();
	}

	for (int i = len-1; i >= 0; i--)
	{
		cout << input[i];
	}

	cout << endl;
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值