Leet Code problem 1410: – HTML Entity Parser

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 ".
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 the 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.

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 &

Flow Diagram: –

Solution :-

class Solution {
    public String entityParser(String text) {
        char []temp = text.toCharArray();
        int j = 0;
        StringBuilder result = new StringBuilder();
        Map<String,String> map = new HashMap();
        
        //Initialize map
        map.put("quot","\"");
        map.put("apos","\'");
        map.put("amp","&");
        map.put("gt",">");
        map.put("lt","<");
        map.put("frasl","/");

        
        for(int i = 0 ; i < temp.length; i++){
            if(temp[i] == '&'){
                StringBuilder sb = new StringBuilder();
                j = i+1;
                while( j< temp.length && temp[j] != ';'){
                    sb.append(temp[j]);
                    j++;
                }  
                String temp2 = sb.toString();
                if(map.get(temp2) != null){
                    result.append(map.get(temp2));
                    i = j;
                }else{
                    result.append('&');
                }
            }else{
                result.append(temp[i]);
            }
        }
        return result.toString();
    }
}