Petya recieved a gift of a string s with length upto 105 characters for his birthday. He took two more emptystrings t and u and decided to play a game. Thisgame has two possible moves:
- Extract the first character of s and append t with this character.
- Extract the last character of t and append u with this character.
Petya wants to get strings s and t emptyand string u lexicographicallyminimal.
You should write a program that will help Petya winthe game.
Input
First line contains non-empty string s (1 ≤ |s| ≤ 105),consisting of lowercase English letters.
Output
Print resulting string u.
Examples
Input
cab
Output
abc
Input
acdb
Output
abdc
题解:就是将字符串s入栈t,然后再出栈,找出之中按最小字典序出栈的一个解
因为出栈时,栈顶的会先出,最小字典序,那么最小的一定先出,即在栈顶,那么我们每次判断栈顶的元素是不是最小的元素即可,这里判断就是按比栈顶元素都小的元素是不是已经没有了来判断,如果是最小的元素,那么就出栈,如果不是,说明最小的元素还没有入栈,就继续入栈,每次都判断栈顶元素即可
#include<bits/stdc++.h>
#include<vector>
#include<stack>
using namespace std;
int main()
{
char s[110];
int vis[30];
vector<char>u;
stack<char>t;
while(~scanf("%s",s)){
memset(vis,0,sizeof(vis));
u.clear();
while(!t.empty())
t.pop();
for(int i = 0; i < strlen(s); i++){ //记录每个字母的数量
vis[s[i]-'a']++;
}
for(int i = 0; i < strlen(s); i++){
t.push(s[i]);
vis[s[i]-'a']--;
int flag = 1;
while(!t.empty()){ //判断栈顶是不是当前情况下最小的字符,若是,则加入u
char c = t.top();
for(int i = 0; i < c-'a'; i++){
if (vis[i]){ //vis不等于0说明c不是最小的字符,退出
flag = 0;
break;
}
}
if (flag == 0){ //flag == 0说明不是最小的字符,继续入栈
break;
}
//是最小的字符,出栈加到u
u.push_back(c);
t.pop();
}
}
for(int i = 0; i < strlen(s); i++)
printf("%c",u[i]);
cout << endl;
}
return 0;
}