两种操作:
1)提出s的首字母添加到t字符串的尾部
2)提出t字符串的尾部字母添加到u字符串的尾部
当s, t 为空后,所能得到的字典序最小的字符串u;
题目分析:
记录每个字母出现的次数
对s字符串进行遍历,对当前遍历的位置i, 得到字母s[i] 加入到stack栈中, 根据输入的字母判断 (i+1)到结束 是否存在字母x < 栈首字母y;
如果没有,出栈。 反之继续进行遍历;
具体细节参见代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = (int)1e5+5; int top, ch[26]; char s[maxn], Stack[maxn], u[maxn]; // u字符串存储最后的答案; bool calc(char u){ // false 表示没有找到; int v = u-'a'; for(int i = 0; i < v; ++i){ if(ch[i] != 0) return true; } return false; } int main() { scanf("%s", s); int len = strlen(s); for(int i = 0; i < len; ++i) ch[s[i]-'a']++; top = 0; int r = 0; // r表示 字符串u当前的长度; for(int i = 0; i < len; ++i){ ch[s[i]-'a']--; Stack[top++] = s[i]; while(top > 0 && calc(Stack[top-1])==false){ u[r++] = Stack[--top]; } } u[r++] = '\0'; printf("%s", u); }