本文介绍: 利用哈希表可解决replaceall更加直接。

「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。

HTML 里这些特殊字符和它们对应字符实体包括:

给你输入字符串 text ,请你实现一个 HTML 实体解析器返回解析器解析后的结果

示例 1:

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

示例 2:

输入text = "and I quote: "...""
输出"and I quote: "...""

示例 3:

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

示例 4:

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

示例 5:

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

思路一:模拟题意(哈希替换

c++解法

class Solution {
public:
    string entityParser(string s) {
        map<string, char&gt; mp;
        mp["quot"] = '"';
        mp["apos"] = ''';
        mp["amp"] = '&';
        mp["gt"] = '&gt;';
        mp["lt"] = '<';
        mp["frasl"] = '/';
        string ans = "";
        int i = 0, j = 0, n = s.size();
        while (i < n) {
            if (s[i] != '&') {
                ans += s[i];
                i++;
                j++;
            } else {
                j = i;
                while (j < n && s[j] != ';') ++j;
                string t = s.substr(i + 1, j - i - 1);
                if (mp.find(t) == mp.end()) {
                    ans += s[i];
                    ++i, ++j;
                    continue;
                }
                ans += mp[t];
                i = j + 1;
            }
        }
        return ans;
        

    }
};

分析

本题考察对字符串的替换,可直接使用replace进行替换,也可将对应字符存入哈希表中,一旦读取到对应字符串则将其替换为哈希表中对应字符串

总结

利用哈希表可解决replaceall更加直接

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注