#1410

HTML Entity Parser

Medium
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the string while utilizing a mapping of HTML entities to their corresponding characters. This allows for efficient replacements without needing to check each character multiple times.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a dictionary to map HTML entities to their corresponding characters.
  2. 2Step 2: Initialize an empty result string.
  3. 3Step 3: Use a while loop to iterate through the input string.
  4. 4Step 4: If the current character is '&', check if the next characters form a valid entity using the dictionary.
  5. 5Step 5: If a valid entity is found, append the corresponding character to the result string; otherwise, append the original character.
  6. 6Step 6: Return the result string.
solution.py28 lines
1# Full working Python code
2
3def entityParser(text):
4    entity_map = {
5        '"': '"',
6        ''': '\',
7        '&': '&',
8        '>': '>',
9        '&lt;': '<',
10        '&frasl;': '/'
11    }
12    result = ''
13    i = 0
14    while i < len(text):
15        if text[i] == '&':
16            for entity in entity_map:
17                if text.startswith(entity, i):
18                    result += entity_map[entity]
19                    i += len(entity)
20                    break
21            else:
22                result += text[i]
23                i += 1
24        else:
25            result += text[i]
26            i += 1
27    return result
28

Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the storage of the result string.

  • 1Using a mapping for replacements can significantly reduce the complexity.
  • 2Single-pass algorithms are often more efficient than nested iterations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.