題目: UVa - 11988 - Broken Keyboard (a.k.a. Beiju Text)

題目說明

給 String,模擬鍵盤輸入的情況,'[' 為 home 鍵,']' 為 end 鍵,求模擬輸出後的字串為何。

解題思路

使用 List 儲存結果,使用 iterator 紀錄目前游標的位置,遍歷 String,當碰到 '['it 更新為 begin(),碰到 ']'it 更新為 end(),其餘情況則使用 insert() 將字元放入即可。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <list>
#include <string>

using namespace std;

static auto __ = []
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
return 0;
}();

int main()
{
string str;
while (getline(cin, str) && !str.empty())
{
list<char> l;
auto it = l.begin();
for (auto& ch : str)
{
switch (ch)
{
case '[':
it = l.begin();
break;
case ']':
it = l.end();
break;
default:
l.insert(it, ch);
break;
}
}
for (auto& ch : l) cout << ch;
cout << '\n';
}
}