HTML Entity Parser — LeetCode 1410 Python Solution
- Problem
- #1410
- Pattern
- Hash Map
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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 ".
Example
- 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 &
Python solution
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
| Measure | Complexity |
|---|---|
| Time | O(n \times l) |
| Space | O(l) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1410. HTML Entity Parser is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1410. HTML Entity Parser?
- LeetCode 1410. HTML Entity Parser is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1410. HTML Entity Parser?
- The Python solution on this page runs in O(n \times l).
- What is the space complexity of LeetCode 1410. HTML Entity Parser?
- The Python solution on this page uses O(l) auxiliary space.
- What topics does LeetCode 1410. HTML Entity Parser cover?
- LeetCode 1410. HTML Entity Parser is tagged Hash Table and String on LeetCode.