[LeetCode in Python] 5382 ,M html entity parser HTML 实体解析器

题目:

https://leetcode-cn.com/problems/html-entity-parser/

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

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

双引号:字符实体为",对应的字符是"

单引号:字符实体为',对应的字符是'

与符号:字符实体为&,对应对的字符是&

大于号:字符实体为>,对应的字符是>

小于号:字符实体为&lt;,对应的字符是<

斜线号:字符实体为&frasl;,对应的字符是/

给你输入字符串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 字符中的任意字符。

解题思路

  • 这种parse题,最无脑的做法就是有限状态机。
  • 观察题目,其实只需要两个状态即可。
  • 一个状态是非特殊词,另一个状态是特殊词
  • 初始状态为非特殊词,状态迁移条件是遇到&字符。
  • 特殊词状态,状态迁移条件是遇到;字符。
  • 无脑按照状态判断及迁移来写就好。

代码

class Solution:
    def entityParser(self, text: str) -> str:
        special_dict = {
            'quot':'"',
            'apos':"'",
            'amp': '&', 
            'gt':'>',
            'lt':'<',
            'frasl':'/',
        }
        
        is_special = False
        special_str = ''
        res = []
        for c in text:
            if is_special:
                if c == ';':
                    if special_str in special_dict:
                        res.append(special_dict[special_str])
                    else:
                        # - if not special, save as is
                        res.append('&%s;' % special_str)
                        
                    special_str = ''
                    is_special = False
                else:
                    special_str += c
            else:
                if c == '&':
                    special_str = ''
                    is_special = True
                else:
                    res.append(c)
        
        return ''.join(res)