2023-11-23
难度 中等
原题
1410. HTML 实体解析器 - 力扣(LeetCode)
「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 > y && x < y is always false"示例 5:
输入:text = "leetcode.com⁄problemset⁄all" 输出:"leetcode.com/problemset/all"
解法
没啥好说的,直接用replace替换,这一题我也用过逐个读取字符,但是效率低错误率高速度慢,730ms,虽然也秒掉了5%的倒霉蛋
直接替换
public String entityParser(String text) {
text=text.replace(""", "\"");//引号需要转义符
text=text.replace("'", "'");
text=text.replace(">", ">");
text=text.replace("<", "<");
text=text.replace("⁄", "/");
text=text.replace("&", "&");
return text;
}
注意踩坑,要替换的包含&,如果提前转换了&会导致后面错误替换,比如要转换的字符串是 “&gt;”,如果先转换了&最后转换的结果就是 > ,正确结果应该是>,所以要把&放到最后一行
另外还有我自己写的低效率的方法,有兴趣可以看看
public String entityParser(String text) {
Map map = new HashMap<>();
map.put(""", "\"");
map.put("'", "'");
map.put("&", "&");
map.put(">", ">");
map.put("<", "<");
map.put("⁄", "/");
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;
}