HTML Entity Parser Problem
Description
LeetCode Problem 1410.
HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
The special characters and their entities for HTML are:
- Quotation Mark: the entity is
"and symbol character is". - Single Quote Mark: the entity is
'and symbol character is'. - Ampersand: the entity is
&and symbol character is&. - Greater Than Sign: the entity is
>and symbol character is>. - Less Than Sign: the entity is
<and symbol character is<. - Slash: the entity is
⁄and symbol character is/.
Given the input text string to the HTML parser, you have to implement the entity parser.
Return the text after replacing the entities by the special characters.
Example 1:
Input: text = "& is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
Explanation: The parser will replace the & entity by &
Example 2:
Input: text = "and I quote: "...""
Output: "and I quote: \"...\""
Constraints:
1 <= text.length <= 10^5- The string may contain any possible characters out of all the 256 ASCII characters.
Solution
Approach: One Left-to-Right Scan
There are only six entities, and each one starts with &. So we scan the text once and build the output as we go:
- If the current character is
&, check whether one of the six entities (",',&,>,<,⁄) starts here. If so, append its character and jump past the whole entity. - Otherwise (any other character, or an
&that does not start an entity, like&ambassador;), copy the character and move on by one.
The tricky case is text like &gt;. Its correct output is >, not >: the & produced by & is output, not input, and must not be parsed again. Because we only read from the original text and jump past each replaced entity, this comes out right. Calling a string "replace all" for each entity in turn would get it wrong if & were replaced before >.
Complexity: O(n) time, since at each position we compare against six entities of at most 7 characters, and O(n) space for the output.
class Solution:
def entityParser(self, text: str) -> str:
entities = {
""": '"',
"'": "'",
"&": "&",
">": ">",
"<": "<",
"⁄": "/",
}
ans = []
i, n = 0, len(text)
while i < n:
if text[i] == "&":
for name, ch in entities.items():
if text.startswith(name, i):
ans.append(ch)
i += len(name) # skip the whole entity; its output is never parsed again
break
else:
ans.append("&")
i += 1
else:
ans.append(text[i])
i += 1
return "".join(ans)