Educational Codeforces Round 19 C. Minimal string

C. Minimal string
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Petya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game 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 empty and string u lexigraphically minimal.

You should write a program that will help Petya win the 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, u;

两种操作:

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);
}


         


猜你喜欢

转载自blog.csdn.net/wangzhuo0978/article/details/70232202