Input: text ="& is an HTML entity but &ambassador; is not."Output: "& is an HTML entity but &ambassador; is not."Explanation: The parser will replace the & entity by &
We can use a hash map to store all HTML entities and their corresponding characters. Then, we scan the string and replace each entity with its character. This is efficient and easy to maintain.
classSolution {
public String entityParser(String text) {
String[][] rep = {
{""", "\""},
{"'", "'"},
{"&", "&"},
{">", ">"},
{"<", "<"},
{"⁄", "/"}
};
for (String[] r : rep) {
text = text.replace(r[0], r[1]);
}
return text;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funentityParser(text: String): String {
val rep = listOf(
""" to '"',
"'" to '\'',
"&" to '&',
">" to '>',
"<" to '<',
"⁄" to '/' )
var ans = text
for ((k, v) in rep) ans = ans.replace(k, v.toString())
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defentityParser(self, text: str) -> str:
rep = {
'"': '"',
''': "'",
'&': '&',
'>': '>',
'<': '<',
'⁄': '/',
}
for k, v in rep.items():
text = text.replace(k, v)
return text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnentity_parser(text: String) -> String {
letmut t = text;
let rep = [
(""", "\""),
("'", "'"),
("&", "&"),
(">", ">"),
("<", "<"),
("⁄", "/"),
];
for (k, v) in rep.iter() {
t = t.replace(k, v);
}
t
}
}