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


相关推荐
老赵的博客20 分钟前
c++面试之从虚函数表到Rtti一次性讲清楚
c++·qt
Navigator_Z23 分钟前
LeetCode //C - 1248. Count Number of Nice Subarrays
c语言·算法·leetcode
傲世仙尊2 小时前
System V 进程间通信详解:共享内存、消息队列与信号量(CSDN博客)
linux·开发语言·c++
cvby2 小时前
C++11
开发语言·c++
6Hzlia2 小时前
【Classic 150 刷题计划】 LeetCode 26. 删除有序数组中的重复项 | C++ 快慢双指针经典模板
c++·算法·leetcode
夜不会漫长3 小时前
C++:类和对象(2)
java·javascript·c++
土司大王3 小时前
LeetCode hot100——74.搜索二维矩阵:Java 二分模板
java·算法·leetcode
无小道3 小时前
C++ 中 `explicit` 关键字详解:彻底理解隐式类型转换
c++·explicit
蒸蒸yyyyzwd3 小时前
cpp 选手秋招学习笔记 day34
c++·八股
Tairitsu_H3 小时前
[C++] C++11类和STL的新特性
开发语言·c++·stl·c++11