一道纯水小模拟。
注意判定字符串合法性。递归里外都要判。
纯纯的 map
模拟,打标记,递归,只要有二级语法水平都能写。
我写了整整 15 分钟,调试整整 20 分钟,所以连二级都没有。
递归里没判合法性,直接卡我 15 分钟。
#include <bits/stdc++.h>
using namespace std;
int T;
string s;
map<string, bool> used, st;
map<string, string> dfn;
bool check(char ch) {
if (ch >= '0' && ch <= '9') return 1;
if (ch >= 'a' && ch <= 'z') return 1;
if (ch >= 'A' && ch <= 'Z') return 1;
if (ch == '_') return 1;
return 0;
}
string solve(string str) {
if (!used[str] || st[str]) return str;
string p = str;
st[str] = 1;
str = dfn[str];
int n = str.size();
string s = "", ans = "";
int id = 0;
while (id < n) {
while (check(str[id]) && id < n) s += str[id], id++;
ans += solve(s), s = "";
while (!check(str[id]) && id < n) ans += str[id], id++;
}
if (s.size()) ans += solve(s);
st[p] = 0;
return ans;
}
int main() {
scanf("%d", &T);
getline(cin, s);
for (int Tid = 1; Tid <= T; Tid++) {
getline(cin, s);
int n = s.size();
// cout << s << endl;
if (s[0] == '#' && s[1] == 'd') { //#define
string s1 = "", s2 = ""; int pos = 0;
for (int i = 8; i < n; i++) {
if (s[i] == ' ') { pos = i; break; }
s1 += s[i];
}
for (int i = pos + 1; i < n; i++) {
// if (s[i] == ' ') break;
s2 += s[i];
}
used[s1] = 1, dfn[s1] = s2;
putchar('\n');
} else if (s[0] == '#' && s[1] == 'u') { //undef
string s1 = "", s2 = ""; int pos = 0;
for (int i = 7; i < n; i++) {
if (s[i] == ' ') { pos = i; break; }
s1 += s[i];
}
for (int i = pos + 1; i < n; i++) s2 += s[i];
used[s1] = 0, dfn[s1] = "";
putchar('\n');
} else {
string str = "";
int id = 0;
while (id < n) {
str = "";
while (check(s[id]) && id < n) str += s[id], id++;
cout << solve(str);
while (!check(s[id]) && id < n) cout << s[id], id++;
}
putchar('\n');
}
}
return 0;
}