LeetCode 1410. HTML 实体解析器:字符串匹配

【LetMeFly】1410.HTML 实体解析器:字符串匹配

力扣题目链接:https://leetcode.cn/problems/html-entity-parser/

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

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

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

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

 

示例 1:

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

示例 2:

输入:text = "and I quote: "...""
输出:"and I quote: \"...\""

示例 3:

输入:text = "Stay home! Practice on Leetcode :)"
输出:"Stay home! Practice on Leetcode :)"

示例 4:

输入:text = "x > y && x < y is always false"
输出:"x > y && x < y is always false"

示例 5:

输入:text = "leetcode.com⁄problemset⁄all"
输出:"leetcode.com/problemset/all"

 

提示:

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

方法一:字符串匹配

一共就6种要替换的情况,我们可以先把6种要替换的情况都存下来到一个数组中(理解为哈希表也可以)。

接着就开始愉快地遍历text字符串了:

  • 如果当前字符为&
    • 遍历替换数组,如果能匹配则将答案字符串加上要替换的结果
    • 如果全部匹配不上就加上当前字符
  • 否则:答案字符串加上当前字符

最终返回答案字符串即可。

  • 时间复杂度 O ( l e n ( t e x t ) × k ) O(len(text)\times k) O(len(text)×k),其中 k k k是要替换字符串的评价长度
  • 空间复杂度 O ( C ) O(C) O(C),只有“替换数组”占据了常数大小的空间

AC代码

C++
const static vector<pair<string, char>> dic = {
    {""", '"'},
    {"'", '\''},
    {"&", '&'},
    {">", '>'},
    {"<", '<'},
    {"⁄", '/'}
};

class Solution {
public:
    string entityParser(string& text) {
        string ans;
        for (int i = 0; i < text.size(); i++) {
            if (text[i] == '&') {
                for (auto&& [from, to] : dic) {
                    if (text.substr(i, from.size()) == from) {
                        ans += to;
                        i += from.size() - 1;
                        goto loop;
                    }
                }
            }
            ans += text[i];
            loop:;
        }
        return ans;
    }
};
Python
dic = [
    ('"', '"'),
    (''', "'"),
    ('>', '>'),
    ('<', '<'),
    ('⁄', '/'),
    ('&', '&')
]

class Solution:
    def entityParser(self, text: str) -> str:
        ans = ''
        i = 0
        while i < len(text):
            matched = False
            if text[i] == '&':
                for from_, to in dic:
                    if text[i: len(from_) + i] == from_:
                        matched = True
                        ans += to
                        i += len(from_)
                        break
            if not matched:
                ans += text[i]
                i += 1
        return ans

同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/134571778

你可能感兴趣的:(题解,#,力扣LeetCode,leetcode,html,题解,力扣,字符串)