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中的字符串逐个判断是否相等。


相关推荐
派大星~课堂17 分钟前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
会编程的土豆1 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
所以遗憾是什么呢?3 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
白藏y3 小时前
【C++】muduo接口补充
开发语言·c++·muduo
xiaoye-duck4 小时前
《算法题讲解指南:递归,搜索与回溯算法--综合练习》--14.找出所有子集的异或总和再求和,15.全排列Ⅱ,16.电话号码的字母组合,17.括号生成
c++·算法·深度优先·回溯
OOJO4 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
Tanecious.4 小时前
蓝桥杯备赛:Day5-P1706 全排列问题
c++·蓝桥杯
胖咕噜的稞达鸭5 小时前
C++技术岗面试经验总结
开发语言·网络·c++·网络协议·tcp/ip·面试
Wild_Pointer.5 小时前
高效工具实战指南:从零开始编写CMakeLists
c++