编辑
2023-11-25
算法题
00
请注意,本文编写于 532 天前,最后修改于 532 天前,其中某些信息可能已经过时。

题目

状态机

很容易有一种思路就是状态机,因为这题状态很少,只有两个,实体,非实体,编译器和解释器本身就是个状态机

cpp
class 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 == "&quot;") return "\""; if (entity == "&apos;") return "'"; if (entity == "&amp;") return "&"; if (entity == "&gt;") return ">"; if (entity == "&lt;") return "<"; if (entity == "&frasl;") return "/"; return entity; // 未知实体,保持不变 } };

字符串替换

cpp
class Solution { public: string entityParser(string text) { unordered_map<string, string> entityMap = { {"&quot;", "\""}, {"&apos;", "'"}, {"&amp;", "&"}, {"&gt;", ">"}, {"&lt;", "<"}, {"&frasl;", "/"} }; 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 许可协议。转载请注明出处!