LeetCode 题解工作台
HTML 实体解析器
「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。 HTML 里这些特殊字符和它们对应的字符实体包括: 双引号: 字符实体为 " ,对应的字符是 " 。 单引号: 字符实体为 ' ,对应的字符是 ' 。 与符号: 字符实体…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
我们可以使用哈希表来存储每个字符实体对应的字符,然后遍历字符串,当遇到字符实体时,我们就将其替换为对应的字符。 时间复杂度 $O(n \times l)$,空间复杂度 。其中 是字符串的长度,而 是字符实体的总长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
「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 字符中的任意字符。
解题思路
方法一:哈希表 + 模拟
我们可以使用哈希表来存储每个字符实体对应的字符,然后遍历字符串,当遇到字符实体时,我们就将其替换为对应的字符。
时间复杂度 ,空间复杂度 。其中 是字符串的长度,而 是字符实体的总长度。
class Solution:
def entityParser(self, text: str) -> str:
d = {
'"': '"',
''': "'",
'&': "&",
">": '>',
"<": '<',
"⁄": '/',
}
i, n = 0, len(text)
ans = []
while i < n:
for l in range(1, 8):
j = i + l
if text[i:j] in d:
ans.append(d[text[i:j]])
i = j
break
else:
ans.append(text[i])
i += 1
return ''.join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on string length and number of entities, roughly O(n) with hash table lookups. Space complexity is O(1) for the map of entities plus O(n) for the result string. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution that avoids nested loops for each character; the '&' detection is key.
- question_mark
Expect the candidate to use a hash table for constant-time entity lookup.
- question_mark
Check handling of edge cases where sequences resemble entities but are invalid.
常见陷阱
外企场景- error
Failing to match the longest valid entity when multiple could start at the same '&'.
- error
Replacing substrings incorrectly and altering parts of the text that are not valid entities.
- error
Not handling large input efficiently, causing O(n^2) behavior due to repeated string concatenation.
进阶变体
外企场景- arrow_right_alt
Parse a string with only numeric HTML entities like & or & instead of named entities.
- arrow_right_alt
Extend the parser to handle nested or repeated entities in a single text segment.
- arrow_right_alt
Modify the parser to work on a stream of characters instead of a preloaded string, maintaining O(1) lookup.