题目大意:
给定一个字符串,其中可能包含[字符和]字符
被字符[和字符]包括的字符串需要移到字符串头
思路:
解法1,使用双端队列来记录截断的字符串。当遇到[字符时设置标识back为false,遇到]字符时设置标识back为true,如果标识back为true,则将字符串放到队列尾部,否则将字符串放到队列头部。注意在遍历结束后,需要再次根据back将字符串
#include<iostream>
#include <fstream>
#include <string>
#include <deque>
using namespace std;
void fastio()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
int main()
{
fastio();
#ifndef ONLINE_JUDGE
ifstream fin("f:\\OJ\\uva_in.txt");
streambuf* back = cin.rdbuf(fin.rdbuf());
#endif
string line;
while ((getline(cin, line), !cin.eof())) {
string s;
bool back = true;
deque<string> q;
for (size_t i = 0; i < line.length(); ++i) {
if (line[i] != '[' && line[i] != ']') {
s += line[i];
} else {
if (back) {
q.push_back(s);
} else {
q.push_front(s);
}
back = (line[i] == ']');
s = "";
}
}
back ? q.push_back(s) : q.push_front(s);
for (auto& s : q) {
cout << s;
}
cout << endl;
}
#ifndef ONLINE_JUDGE
cin.rdbuf(back);
#endif
return 0;
}
解法2,使用循环链表,用successor[i]表示i的后继字符所在字符串的下标。用tail表示循环链表的尾节点所在的下标,cur表示当前输入字符的位置,当遇到[字符时,将cur设置为0,当遇到]字符时,将cur设置为tail。当处理正常字符时,将字符插入cur对应链表的后面。
#include<iostream>
#include <fstream>
#include <string>
#include <deque>
#include <cstring>
using namespace std;
const int MAXN = 100000 + 10;
char s[MAXN];
int successor[MAXN];
void fastio()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
int main()
{
fastio();
#ifndef ONLINE_JUDGE
ifstream fin("f:\\OJ\\uva_in.txt");
streambuf* back = cin.rdbuf(fin.rdbuf());
#endif
while (cin >> s + 1) {
int cur = 0;
int tail = 0;
successor[0] = 0;
int len = strlen(s + 1);
for (int i = 1; i <= len; ++i) {
if (s[i] == '[') {
cur = 0;
} else if (s[i] == ']'){
cur = tail;
} else {
successor[i] = successor[cur];
successor[cur] = i;
cur = i;
if (successor[cur] == 0) {
tail = cur;
}
}
}
for (int i = successor[0]; i; i = successor[i]) {
cout << s[i];
}
cout << endl;
}
#ifndef ONLINE_JUDGE
cin.rdbuf(back);
#endif
return 0;
}