題目:
1410. HTML 實體解析器
「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"
提示:
1 <= text.length <= 10^5
- 字符串可能包含 256 個ASCII 字符中的任意字符。
解答:
代碼:
class Solution {public String entityParser(String text) {Map<String,String> map=new HashMap<>();map.put(""","\"");map.put("'","'");map.put("&","&");map.put(">",">");map.put("<","<");map.put("⁄","/");int n=text.length();StringBuilder sb=new StringBuilder();for(int i=0;i<n;){if(text.charAt(i)=='&'){int j=i+1;while(j<n&&j-i<6&&text.charAt(j)!=';') j++;String sub=text.substring(i,Math.min(j+1,n));if(map.containsKey(sub)){sb.append(map.get(sub));i=j+1;continue;}}sb.append(text.charAt(i++));}return sb.toString();}
}