Similar Problems

Similar Problems not available

Html Entity Parser - Leetcode Solution

Companies:

LeetCode:  Html Entity Parser Leetcode Solution

Difficulty: Medium

Topics: string hash-table  

Problem Statement:

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

The special characters and their entities for HTML are:

  • ' & ' (ampersand) becomes '&'
  • ' " ' (double quote) becomes '"'
  • ' ' ' (single quote) becomes '''
  • ' > ' (greater than) becomes '>'
  • ' < ' (less than) becomes '<'
  • ' / ' (slash) becomes '⁄'

Given the input text string containing HTML entities, you need to convert this text string into the plain text format by replacing all the entities with their original characters.

Example 1:

Input: " & is an HTML entity but &ambassador; is not." Output: " & is an HTML entity but &ambassador; is not." Explanation: The entity & is replaced by &

Example 2:

Input: "leetcode.com⁄problemset⁄all" Output: "leetcode.com/problemset/all" Explanation: The entity ⁄ is replaced by /.

Solution:

The Html Entity Parser problem can be solved using simple string manipulation techniques, where we iterate over the input string and replace the entities of special characters with their original characters as per the given HTML standard.

Here is the step by step approach to solving this problem:

  1. Create a hashmap to store the special characters and their corresponding entities.

    HashMap<String, String> map = new HashMap<>(); map.put(""", """); map.put("'", "'"); map.put("&", "&"); map.put(">", ">"); map.put("<", "<"); map.put("⁄", "/");

  2. Iterate over the input string and replace each entity with its original special character.

    for (String key : map.keySet()) { while (text.indexOf(key) >= 0) { text = text.replace(key, map.get(key)); } }

  3. Return the converted plain text.

    return text;

Complete Java code:

class Solution { public String entityParser(String text) {

    HashMap<String, String> map = new HashMap<>();
    map.put("&quot;", "\"");
    map.put("&apos;", "'");
    map.put("&amp;", "&");
    map.put("&gt;", ">");
    map.put("&lt;", "<");
    map.put("&frasl;", "/");
    
    for (String key : map.keySet()) {
        while (text.indexOf(key) >= 0) {
            text = text.replace(key, map.get(key));
        }
    }
    
    return text;
}

}

Time Complexity: O(N*M), where N is the length of the input string and M is the maximum length of the entity to be replaced.

Space Complexity: O(M), where M is the number of entities in the hashmap.

Html Entity Parser Solution Code

1