力扣 1410 HTML实体解析器

2023-11-23

难度 中等

原题

1410. HTML 实体解析器 - 力扣(LeetCode)

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

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

  • 双引号:字符实体为 " ,对应的字符是 " 。
  • 单引号:字符实体为 ' ,对应的字符是 ' 。
  • 与符号:字符实体为 & ,对应对的字符是 & 。
  • 大于号:字符实体为 > ,对应的字符是 > 。
  • 小于号:字符实体为 &lt; ,对应的字符是 < 。
  • 斜线号:字符实体为 &frasl; ,对应的字符是 / 。

给你输入字符串 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"
解法

         没啥好说的,直接用replace替换,这一题我也用过逐个读取字符,但是效率低错误率高速度慢,730ms,虽然也秒掉了5%的倒霉蛋

直接替换

        public String entityParser(String text) {
            text=text.replace("&quot;", "\"");//引号需要转义符
            text=text.replace("&apos;", "'");
            text=text.replace("&gt;", ">");
            text=text.replace("&lt;", "<");
            text=text.replace("&frasl;", "/");
            text=text.replace("&amp;", "&");
            return text;
        }

注意踩坑,要替换的包含&,如果提前转换了&会导致后面错误替换,比如要转换的字符串是 “&amp;gt;”,如果先转换了&最后转换的结果就是 > ,正确结果应该是&gt;,所以要把&放到最后一行

另外还有我自己写的低效率的方法,有兴趣可以看看

public String entityParser(String text) {
            Map map = new HashMap<>();
            map.put("&quot;", "\"");
            map.put("&apos;", "'");
            map.put("&amp;", "&");
            map.put("&gt;", ">");
            map.put("&lt;", "<");
            map.put("&frasl;", "/");
            int len = text.length();
            String res = "";
            for (int i = 0; i < len; i++) {
                if (text.charAt(i) == '&') {
                    String sub = "&";
                    i++;
                    while (i<len&&text.charAt(i) != ';') {
                        if (text.charAt(i)=='&'){
                            res+=sub;
                            sub="";
                        }
                        sub += text.charAt(i);
                        i++;
                    }
                    if (i<len&&text.charAt(i)==';')
                        sub += ";";
                    if (map.get(sub)!=null) {
                        res += map.get(sub);
                    }else {
                        res+=sub;
                    }
                } else {
                    res += text.charAt(i);
                }
            }
            return res;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值