uva 11988 Broken Keyboard (a.k.a. Beiju Text)

点击打开链接uva 11988

思路: deque模拟
分析:
1 题目给定一个字符串要求通过一序列的模拟输出最后的字符串
2 根据题目的意思[],分别表示的是键盘上的home和end键,home键的作用是跳到起始位置,end的作用是到最后一个位置。
3 根据2我们可以利用双端队列来模拟,如果是[我们插入front,如果是]插入back,最后在输出即可

代码:

#include<deque>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int MAXN = 100010;

char str[MAXN];
deque<string>dqe;

void insert(bool front , bool rear , string s){
    if(front)
        dqe.push_front(s);
    if(rear)
        dqe.push_back(s);
}

void output(){
    while(!dqe.empty()){
         cout<<dqe.front();
         dqe.pop_front();
    }
    puts("");
}

void solve(){
    int len = strlen(str); 
    bool front , rear;
    string s = "";
    front = true;
    rear = false;
    for(int i = 0 ; i < len ; i++){
        if(str[i] == '['){
           insert(front , rear , s);
           s = ""; 
           front = true;
           rear = false;
        }
        else if(str[i] == ']'){
           insert(front , rear , s);
           s = ""; 
           front = false;
           rear = true;
        }
        else{
           s += str[i]; 
        } 
    }
    insert(front , rear , s);
    output();
}

int main(){
    while(scanf("%s" , str) != EOF)
        solve();
    return 0;
}


list 来做

#include<list>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int MAXN = 100010;
list<char>ls;

int main(){
    char str[MAXN];
    while(gets(str)){
         ls.clear();
         int len = strlen(str); 
         list<char>::iterator it = ls.begin();
         for(int i = 0 ; i < len ; i++){
             if(str[i] == '[') 
                it = ls.begin();
             else if(str[i] == ']') 
                it = ls.end();
             else{
                ls.insert(it,str[i]);
             } 
         }
         for(it = ls.begin(); it != ls.end() ; it++)
             printf("%c" , *it);
         puts("");
    } 
    return 0;
}




你可能感兴趣的:(uva 11988 Broken Keyboard (a.k.a. Beiju Text))