-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1410.HTML-Entity-Parser.java
57 lines (45 loc) · 1.54 KB
/
1410.HTML-Entity-Parser.java
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
49
50
51
52
53
54
55
56
57
// https://leetcode.com/problems/html-entity-parser/
// algorithms
// Medium (54.05%)
// Total Accepted: 8,606
// Total Submissions: 15,921
class Solution {
private static final HashMap<String, Character> CHAR_ENTITY = new HashMap<>();
private static final HashSet<Integer> ENTITY_LEN = new HashSet<>();
private static final char BEGIN_CHAR = '&';
static {
CHAR_ENTITY.put(""", '"');
CHAR_ENTITY.put("'", '\'');
CHAR_ENTITY.put("&", '&');
CHAR_ENTITY.put(">", '>');
CHAR_ENTITY.put("<", '<');
CHAR_ENTITY.put("⁄", '/');
for (String key : CHAR_ENTITY.keySet()) {
ENTITY_LEN.add(key.length());
}
}
public String entityParser(String text) {
int curIdx = 0, preIdx = 0;
StringBuilder sb = new StringBuilder();
while ((curIdx = text.indexOf(BEGIN_CHAR, curIdx)) != -1) {
String tmp;
boolean isFound = false;
for (int len : ENTITY_LEN) {
tmp = text.substring(curIdx, curIdx + len);
Character ch = CHAR_ENTITY.get(tmp);
if (ch != null) {
sb.append(text.substring(preIdx, curIdx)).append(ch);
curIdx += len;
preIdx = curIdx;
isFound = true;
break;
}
}
if (!isFound) {
curIdx++;
}
}
sb.append(text.substring(preIdx));
return sb.toString();
}
}