给出一个由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;
}