友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

1410. HTML 实体解析器

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

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

  • 双引号:字符实体为 " ,对应的字符是 "

  • 单引号:字符实体为 ' ,对应的字符是 '

  • 与符号:字符实体为 & ,对应对的字符是 &

  • 大于号:字符实体为 > ,对应的字符是 >

  • 小于号:字符实体为 < ,对应的字符是 <

  • 斜线号:字符实体为 ,对应的字符是 /

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

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

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

示例 5:

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

提示:

  • 1 <= text.length <= 10^5

  • 字符串可能包含 256 个ASCII 字符中的任意字符。

思路分析

将实体存入 Map,然后逐个字符读取,遇到开头 & 和结尾 ; 就专门处理一下。

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2025-05-22 22:59:23
 */
public String entityParser(String text) {
  Map<String, String> map = Map.of(
    "&quot;", "\"",
    "&apos;", "'",
    "&amp;", "&",
    "&gt;", ">",
    "&lt;", "<",
    "&frasl;", "/");
  StringBuilder sb = new StringBuilder();
  boolean flag = false;
  StringBuilder temp = new StringBuilder();
  for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    if (c == '&') {
      if (!temp.isEmpty()) {
        sb.append(temp);
        temp.setLength(0);
      }
      temp.append(c);
      flag = true;
    } else if (c == ';') {
      temp.append(c);
      String entry = temp.toString();
      String s = map.get(entry);
      if (s != null) {
        sb.append(s);
      } else {
        sb.append(entry);
      }
      temp.setLength(0);
      flag = false;
    } else {
      if (flag) {
        temp.append(c);
      } else {
        sb.append(c);
      }
    }
  }
  if (!temp.isEmpty()) {
    sb.append(temp);
  }
  return sb.toString();
}

参考资料