Openjudge 3342 字符串操作
这以题和括号匹配/逆波兰表达式这种有点像
但是由于返回值不同,需要用用栈+递归联合模拟才好做
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <queue>
#include <stack>
using namespace std;
const int MAX_N = 5010;
int n;
string str[MAX_N];
queue<string> command;
stack<string> que;
inline int toInt(string x) { return atoi(x.c_str()); }
inline bool isDigit(string x) {
for (int i = 0; i < x.size(); ++i)
if (x[i] < '0' || x[i] > '9') return false;
if (toInt(x) > 99999 || toInt(x) < 0) return false;
return true;
}
inline string getCommand() {
string s = command.front();
command.pop();
return s;
}
inline string getTop() {
string s = que.top();
que.pop();
return s;
}
void maintain(string& opr) {
while (!command.empty()) command.pop();
opr += " ";
while (!opr.empty()) {
int ed = opr.find_first_of(" ");
command.push(opr.substr(0, ed));
opr = opr.substr(ed + 1);
}
}
void solve() {
string arg = getCommand();
que.push(arg);
if (arg == "copy") {
solve();
int n = toInt(getTop());
solve();
int x = toInt(getTop());
solve();
int l = toInt(getTop());
que.pop();
que.push(str[n].substr(x, l));
return;
}
if (arg == "add") {
solve();
string s1 = getTop();
solve();
string s2 = getTop();
que.pop();
if (isDigit(s1) && isDigit(s2))
que.push(to_string(toInt(s1) + toInt(s2)));
else
que.push(s1 + s2);
return;
}
if (arg == "find" || arg == "rfind") {
solve();
string s = getTop();
solve();
int n = toInt(getTop()), loc;
que.pop();
if (arg == "find")
loc = str[n].find(s);
else
loc = str[n].rfind(s);
if (loc == -1)
loc = s.length();
que.push(to_string(loc));
return;
}
if (arg == "insert") {
solve();
string s = getTop();
solve();
int n = toInt(getTop());
solve();
int x = toInt(getTop());
que.pop();
str[n].insert(x, s);
return;
}
if (arg == "reset") {
solve();
string s = getTop();
solve();
int n = toInt(getTop());
que.pop();
str[n] = s;
return;
}
if (arg == "print") {
solve();
int n = toInt(getTop());
que.pop();
cout << str[n] << endl;
return;
}
if (arg == "printall") {
que.pop();
for (int i = 1; i <= n; ++i)
cout << str[i] << endl;
return;
}
return;
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> str[i];
cin.get();
string opr;
while (getline(cin, opr)) {
if (opr == "over") break;
maintain(opr);
solve();
}
return 0;
}