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


相关推荐
※DX3906※14 分钟前
cpp实战项目—string类的模拟实现
开发语言·c++
Joyner20181 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
因兹菜1 小时前
[LeetCode]day9 203.移除链表元素
算法·leetcode·链表
LNsupermali1 小时前
力扣257. 二叉树的所有路径(遍历思想解决)
算法·leetcode·职场和发展
雾月551 小时前
LeetCode LCR180文件组合
算法·leetcode·职场和发展
萌の鱼1 小时前
leetcode 2080. 区间内查询数字的频率
数据结构·c++·算法·leetcode
Tisfy1 小时前
LeetCode 0541.反转字符串 II:模拟
算法·leetcode·字符串·题解
xianwu5432 小时前
反向代理模块jmh
开发语言·网络·数据库·c++·mysql
labmem13 小时前
Leetcode:541
算法·leetcode·职场和发展
圆圆滚滚小企鹅。4 小时前
刷题记录 HOT100回溯算法-6:79. 单词搜索
笔记·python·算法·leetcode