LeetCode解法汇总1410. HTML 实体解析器

目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

描述:

「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。

HTML 里这些特殊字符和它们对应的字符实体包括:

  • 双引号: 字符实体为 " ,对应的字符是 "
  • 单引号: 字符实体为 ' ,对应的字符是 '
  • 与符号: 字符实体为 & ,对应对的字符是 &
  • 大于号: 字符实体为 > ,对应的字符是 >
  • 小于号: 字符实体为 &lt; ,对应的字符是 <
  • 斜线号: 字符实体为 &frasl; ,对应的字符是 /

给你输入字符串 text ,请你实现一个 HTML 实体解析器,返回解析器解析后的结果。

示例 1:

复制代码
输入:text = "&amp; is an HTML entity but &ambassador; is not."
输出:"& is an HTML entity but &ambassador; is not."
解释:解析器把字符实体 &amp; 用 & 替换

示例 2:

复制代码
输入:text = "and I quote: &quot;...&quot;"
输出:"and I quote: \"...\""

示例 3:

复制代码
输入:text = "Stay home! Practice on Leetcode :)"
输出:"Stay home! Practice on Leetcode :)"

示例 4:

复制代码
输入:text = "x &gt; y &amp;&amp; x &lt; y is always false"
输出:"x > y && x < y is always false"

示例 5:

复制代码
输入:text = "leetcode.com&frasl;problemset&frasl;all"
输出:"leetcode.com/problemset/all"

提示:

  • 1 <= text.length <= 10^5
  • 字符串可能包含 256 个ASCII 字符中的任意字符。

解题思路:

遍历字符串中的每一个字符,如果字符串及其后面的字符可匹配,则index+=匹配的长度。

否则index++即可。

代码:

复制代码
class Solution {
public:
    vector<string> v1 = {"&quot;", "'", "&amp;", "&gt;", "&lt;", "&frasl;"};
    vector<string> v2 = {"\"", "\'", "&", ">", "<", "/"};
    pair<string, int> isMatchReplace(string &text, int index)
    {
        for (int i = 0; i < v1.size(); i++)
        {
            if (text.compare(index, v1[i].size(), v1[i]) == 0)
            {
                int k = v1[i].size();
                return make_pair(static_cast<string>(v2[i]), v1[i].size());
            }
        }
        return make_pair<string, int>(text.substr(index, 1), 1);
    }

    string entityParser(string text)
    {
        int index = 0;
        ostringstream out;
        pair<string, int> pair;
        while (index < text.size())
        {
            pair = isMatchReplace(text, index);
            out << pair.first;
            index += pair.second;
        }
        return out.str();
    }
};
相关推荐
历程里程碑3 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
YGGP4 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
你撅嘴真丑11 小时前
第九章-数字三角形
算法
uesowys11 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder11 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮11 小时前
AI 视觉连载1:像素
算法
智驱力人工智能11 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥12 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风12 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風13 小时前
8.1 PFH&&FPFH
图像处理·算法