DDSA Solutions

1410. HTML Entity Parser

Time: O(n)
Space: O(n)
Advertisement

Intuition

Process HTML entities: & ' " > < Each appears in encoded string, map back to actual characters.

Algorithm

  1. 1String replace or state machine: scan for &...;. Map known entities to characters.
  2. 2Only 5 entities to handle.

Common Pitfalls

  • Only the 5 specified entities: &quot; -> ", &apos; -> ', &amp; -> &, &gt; -> >, &lt; -> <. Process left to right.
1410.cs
C#
// Approach: Sequential string replacement for each HTML entity; process '&amp;' last to avoid double-replacement.
// Time: O(n) Space: O(n)

public class Solution
{
    public string EntityParser(string text)
    {
        var entryToChar = new Dictionary<string, string> {
            { "&quot;", "\"" },
            { "&apos;", "'" },
            { "&gt;", ">" },
            { "&lt;", "<" },
            { "&frasl;", "/" }
        };

        foreach (var entry in entryToChar)
        {
            var entity = entry.Key;
            var c = entry.Value;
            text = text.Replace(entity, c);
        }

        // Process '&' in last.
        return text.Replace("&amp;", "&");
    }
}
Advertisement
Was this solution helpful?