[力扣]5382. HTML 实体解析器

HTML解析

Posted by JinFei on April 12, 2020

题目描述

「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。 HTML 里这些特殊字符和它们对应的字符实体包括: - 双引号:字符实体为 " ,对应的字符是 “ 。 - 单引号:字符实体为 ' ,对应的字符是 ‘ 。 - 与符号:字符实体为 & ,对应对的字符是 & 。 - 大于号:字符实体为 > ,对应的字符是 > 。 - 小于号:字符实体为 < ,对应的字符是 < 。 - 斜线号:字符实体为 ⁄ ,对应的字符是 / 。 给你输入字符串 text ,请你实现一个 HTML 实体解析器,返回解析器解析后的结果。

Example1:

  输入:text = "&amp; is an HTML entity but &ambassador; is not."
    输出:"& is an HTML entity but &ambassador; is not."
    解释:解析器把字符实体 &amp; 用 & 替换

Example2:

  输入:text = "and I quote: &quot;...&quot;"
    输出:"and I quote: \"...\""

Example3:

  输入:text = "Stay home! Practice on Leetcode :)"
    输出:"Stay home! Practice on Leetcode :)"

Example4:

  输入:text = "x &gt; y &amp;&amp; x &lt; y is always false"
    输出:"x > y && x < y is always false"

Example5:

  输入:text = "leetcode.com&frasl;problemset&frasl;all"
    输出:"leetcode.com/problemset/all"

说明:

  • 1 <= text.length <= 10^5
  • 字符串可能包含 256 个ASCII 字符中的任意字符。

思路

  • 字符串解析
  • 看子串是否与给定的相同
class Solution {
public:
    string entityParser(string text) {
        string res;
        for(int i = 0; i < text.size();){
            if(text[i] == '&'){
                if(i + 6 <= text.size() && text.substr(i, 6) == "&quot;"){
                    res += "\"";
                    i += 6;
                }
                else if(i + 6 <= text.size() && text.substr(i, 6) == "&apos;"){
                    res += "'";
                    i += 6;
                }
                else if(i + 5 <= text.size() && text.substr(i, 5) == "&amp;"){
                    res += "&";
                    i += 5;
                }
                else if(i + 4 <= text.size() && text.substr(i, 4) == "&gt;"){
                    res += ">";
                    i += 4;
                }
                else if(i + 4 <= text.size() && text.substr(i, 4) == "&lt;"){
                    res += "<";
                    i += 4;
                }
                else if(i + 7 <= text.size() && text.substr(i, 7) == "&frasl;"){
                    res += "/"; 
                    i += 7;
                }else{
                    res += text[i];
                    i ++;
                }
            }else{
                res += text[i];
                i ++;
            }
        }
        return res;
    }
};