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


相关推荐
ALex_zry13 分钟前
MQTT客户端核心架构解析:clients.h源码深度解读
c++·架构
@hdd22 分钟前
C++ | STL之list详解:双向链表的灵活操作与高效实践
c++·list
Haohao+++23 分钟前
leetcode面试经典算法题——2
算法·leetcode·面试
凤年徐39 分钟前
【C/C++】深入理解指针(二)
c语言·开发语言·c++·经验分享·笔记·指针
冠位观测者1 小时前
【Leetcode 每日一题 - 补卡】1534. 统计好三元组
数据结构·算法·leetcode
weixin_445054722 小时前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
XXYBMOOO2 小时前
基于 Qt 的 BMP 图像数据存取至 SQLite 数据库的实现
数据库·c++·qt
虾球xz2 小时前
游戏引擎学习第230天
c++·学习·游戏引擎
-优势在我3 小时前
LeetCode之两数之和
算法·leetcode
WaitWaitWait013 小时前
LeetCode每日一题4.17
算法·leetcode