给出一个由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<stdio.h> #include<algorithm> #include<string.h> #include<stack> using namespace std; const int maxm = 1000005; char str[maxm], ch[30], sh[30]; int flag[maxm], vis[maxm]; stack<char>s; void PUT(); int main() { int n, i, j, k, sum; scanf("%s", str + 1); memset(flag, 0, sizeof(flag)); memset(vis, 0, sizeof(vis)); for (i = 1;str[i] != '\0';i++) flag[str[i]]++; s.push(str[1]);vis[str[1]] = 1; flag[str[1]]--; for (i = 2;str[i] != '\0';i++) { while (!vis[str[i]] && !s.empty() && str[i] <= s.top() && flag[s.top()]) { vis[s.top()] = 0; s.pop(); } if (!vis[str[i]]) { s.push(str[i]); vis[str[i]] = 1; } flag[str[i]]--; } PUT(); printf("\n"); return 0; } void PUT() { char xx = s.top(); s.pop(); if (!s.empty()) PUT(); printf("%c", xx); }