HTML Entity Parser - Problem

HTML entity parser is the parser that takes HTML code as input and replaces all the entities of the special characters by the characters themselves.

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 &lt; and symbol character is <
  • Slash: the entity is &frasl; and symbol character is /

Given an 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.

Input & Output

Example 1 — Basic Entities
$ Input: text = "&amp; is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
💡 Note: & is a valid entity that gets replaced with &, but &ambassador; is not a valid HTML entity so it stays unchanged
Example 2 — Multiple Entities
$ Input: text = "and I quote: &quot;...&quot;"
Output: "and I quote: \"...\""
💡 Note: " entities are replaced with quotation marks to form: and I quote: "..."
Example 3 — No Valid Entities
$ Input: text = "Stay home! Practice on Leetcode :)"
Output: "Stay home! Practice on Leetcode :)"
💡 Note: No HTML entities present, so the string remains unchanged

Constraints

  • 1 ≤ text.length ≤ 105
  • The string may contain any possible characters out of all the 256 ASCII characters.

Visualization

Tap to expand
HTML Entity Parser Overview&quot;Hello &amp; welcome&quot; she said.Input: HTML text with entitiesEntity ParserReplace entities withactual characters"Hello & welcome" she said.Output: Clean text with actual characters
Understanding the Visualization
1
Input
HTML text with entities like &amp;, &gt;, &quot;
2
Parse
Identify and replace valid HTML entities
3
Output
Clean text with actual characters
Key Takeaway
🎯 Key Insight: Use hash map for O(1) entity lookup during single string traversal
Asked in
Amazon 15 Facebook 12 Google 8 Microsoft 6
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen