很容易有一种思路就是状态机,因为这题状态很少,只有两个,实体,非实体,编译器和解释器本身就是个状态机
cppclass Solution {
public:
string entityParser(string text) {
int state = 0;
string result = "";
string entity = "";
for (char ch : text) {
switch (state) {
case 0:
if (ch == '&') {
state = 1;
entity += ch;
} else {
result += ch;
}
break;
case 1:
if (ch == '&') {
result += entity; // 不是实体,加入结果
entity = "&"; // 重置entity
} else if (ch == ';') {
entity += ch;
result += replaceEntity(entity); // 替换实体并加入结果
entity = ""; // 重置entity
state = 0;
} else {
entity += ch;
}
break;
}
}
if (state == 1) {
result += entity; // 处理结尾的未结束实体
}
return result;
}
private:
string replaceEntity(string entity) {
if (entity == """) return "\"";
if (entity == "'") return "'";
if (entity == "&") return "&";
if (entity == ">") return ">";
if (entity == "<") return "<";
if (entity == "⁄") return "/";
return entity; // 未知实体,保持不变
}
};
cppclass Solution {
public:
string entityParser(string text) {
unordered_map<string, string> entityMap = {
{""", "\""},
{"'", "'"},
{"&", "&"},
{">", ">"},
{"<", "<"},
{"⁄", "/"}
};
for (auto& entry : entityMap) {
size_t pos = 0;
while ((pos = text.find(entry.first, pos)) != string::npos) {
text.replace(pos, entry.first.length(), entry.second);
pos += entry.second.length();
}
}
return text;
}
};
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!