1. 程式人生 > 其它 >UVA - 11988 - Broken Keyboard (a.k.a. Beiju Text)

UVA - 11988 - Broken Keyboard (a.k.a. Beiju Text)

技術標籤:C++

題目:

破損的鍵盤(又名:悲劇文字)

方法一:陣列模擬

#include<bits/stdc++.h> // 最快

using namespace std;

const int maxn = 1e5 + 10;
int a[maxn];
char s[maxn];

int main() {
	while(scanf("%s", s + 1) == 1) {
		memset(a, 0, sizeof(a));
		int cur = 0, last = 0;
		for(int i = 1; i <= strlen(s + 1); i++
) { if(s[i] == '[') cur = 0; else if(s[i] == ']') cur = last; else { a[i] = a[cur]; a[cur] = i; if(cur == last) last = i; cur = i; } } for(int i = a[0]; i != 0; i = a[i]) printf("%c", s[i]); printf("\n"); } return 0; }

方法二:連結串列 list

#include<bits/stdc++.h>
using namespace std; int main() { string s; while(cin >> s) { list<char> l; list<char>::iterator p = l.begin(); for(int i = 0; i < s.size(); i++) { if(s[i] == '[') p = l.begin(); else if(s[i] == ']') p = l.end(); else l.insert(p, s[i]); } for(list<char>
::iterator it = l.begin(); it != l.end(); it++) printf("%c", *it); printf("\n"); } return 0; }

方法三:雙端佇列 deque

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string str;
    while(getline(cin, str)){
        int len = str.size();
        deque<string> ll;
        string data;
        bool bb = true;
        for(int i = 0; i < len; i++) {
            if(str[i] != '[' && str[i] != ']') data += str[i];
            else{
                bb ? ll.push_back(data) : ll.push_front(data);
                bb = str[i] == ']';
                data = "";
            }
        }
        bb ? ll.push_back(data) : ll.push_front(data);
        for(const auto& e : ll) cout << e;
        cout << endl;
    }

    return 0;
}