1410.HTML 实体解析器

​​题目来源:

leetcode题目,网址:1410. HTML 实体解析器 - 力扣(LeetCode)

解题思路:

使用map存放特殊字符串及其应被替换为的字符串。然后遍历字符串替换 map 中的字符串即可。

解题代码:

复制代码
class Solution {
public:
    string entityParser(string text) {
        unordered_map<string,string> map=getMap();
        string res="";
        for(int i=0;i<text.length();i++){
            if(text[i]!='&'|| i==text.length()-1){
                res+=text[i];
            }else{
                for(int j=i+1;j<text.length();j++){
                    if(text[j]=='&'){
                        res+=text.substr(i,j-i);
                        i=j-1;
                        break;
                    }else if(text[j]==';'){
                        string temp=text.substr(i,j-i+1);
                        if(map.count(temp)==0){
                            res+=text.substr(i,j-i+1);
                        }else{
                            res+=map[temp];
                        }
                        i=j;
                        break;
                    }else if(j==text.length()-1){
                        res+=text.substr(i,j-i+1);
                        i=j;
                        break;
                    }
                }
            }
        }
        return res;
    }
    unordered_map<string,string> getMap(){
        unordered_map<string,string> res;
        res["&quot;"]="\"";
        res["'"]="\'";
        res["&amp;"]="&";
        res["&gt;"]=">";
        res["&lt;"]="<";
        res["&frasl;"]="/";
        return res;
    }
};
复制代码

总结:

官方题解也是模拟,不过他在每一个 & 字符处对map中的字符串逐个判断是否相等。


相关推荐
clint4564 天前
C++进阶(1)——前景提要
c++
夜悊4 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴4 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0015 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾5 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you5 天前
constexpr函数
c++
凡人叶枫5 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫5 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss5 天前
BRpc使用
c++·rpc
-森屿安年-5 天前
63. 不同路径 II
c++·算法·动态规划