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


相关推荐
xyx-3v32 分钟前
qt创建新工程
开发语言·c++·qt
样例过了就是过了1 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
少司府1 小时前
C++基础入门:类和对象(中)
c语言·开发语言·c++·类和对象·运算符重载·默认成员函数
ThisIsMirror1 小时前
leetcode 452 Arrays.sort()排序整数溢出、Integer.compare(a[1], b[1])成功的问题
算法·leetcode
王老师青少年编程1 小时前
csp信奥赛c++之状压枚举
数据结构·c++·算法·csp·信奥赛·csp-s·状压枚举
x_xbx2 小时前
LeetCode:438. 找到字符串中所有字母异位词
算法·leetcode·职场和发展
ysa0510302 小时前
斐波那契上斐波那契【矩阵快速幂】
数据结构·c++·笔记·算法
派大星~课堂3 小时前
【力扣-94.二叉树的中序遍历】Python笔记
笔记·python·leetcode
AI成长日志3 小时前
【笔面试算法学习专栏】堆与优先队列实战:力扣hot100之215.数组中的第K个最大元素、347.前K个高频元素
学习·算法·leetcode
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 45. 跳跃游戏 II | C++ 贪心算法最优解题解
c++·leetcode·游戏