题目是LeetCode第184场周赛的第三题,链接:HTML 实体解析器。具体描述可见原题。
这虽然是道medium的题目,但其实就很简单,在遍历字符串的时候,一遇到&
的时候就判断后面紧接着的连续几个字符组合起来能否构成题目给定的六种特殊字符串即可,虽然这么做代码稍显繁琐,但是快啊。时间复杂度为
O
(
n
)
O(n)
O(n),空间复杂度为
O
(
n
)
O(n)
O(n)(这里是因为我用了字符数组而不直接用字符串,因为直接用字符串操作还是慢,虽然空间复杂度可以降为
O
(
1
)
O(1)
O(1))。
JAVA版代码如下:
class Solution {
public String entityParser(String text) {
char[] chars = text.toCharArray();
char[] result = new char[chars.length];
int idx = 0;
int i = 0;
while(i < chars.length) {
boolean add = false;
if (chars[i] == '&') {
if (i + 6 < chars.length) {
if (chars[i + 1] == 'f' && chars[i + 2] == 'r' && chars[i + 3] == 'a' && chars[i + 4] == 's' && chars[i + 5] == 'l' && chars[i + 6] == ';') {
result[idx++] = '/';
add = true;
i += 7;
continue;
}
}
if (i + 5 < chars.length) {
if (chars[i + 1] == 'q' && chars[i + 2] == 'u' && chars[i + 3] == 'o' && chars[i + 4] == 't' && chars[i + 5] == ';') {
result[idx++] = '\"';
add = true;
i += 6;
continue;
}
else if (chars[i + 1] == 'a' && chars[i + 2] == 'p' && chars[i + 3] == 'o' && chars[i + 4] == 's' && chars[i + 5] == ';') {
result[idx++] = '\'';
add = true;
i += 6;
continue;
}
}
if (i + 4 < chars.length) {
if (chars[i + 1] == 'a' && chars[i + 2] == 'm' && chars[i + 3] == 'p' && chars[i + 4] == ';') {
result[idx++] = '&';
add = true;
i += 5;
continue;
}
}
if (i + 3 < chars.length) {
if (chars[i + 1] == 'g' && chars[i + 2] == 't' && chars[i + 3] == ';') {
result[idx++] = '>';
add = true;
i += 4;
continue;
}
else if (chars[i + 1] == 'l' && chars[i + 2] == 't' && chars[i + 3] == ';') {
result[idx++] = '<';
add = true;
i += 4;
continue;
}
}
}
if (!add) {
result[idx++] = chars[i++];
}
}
return new String(result, 0, idx);
}
}
提交结果如下:
Python版代码如下(直接调用replace()
更快,注意要把对&
的替换放到最后):
class Solution:
def entityParser(self, text: str) -> str:
text = text.replace('⁄', '/')
text = text.replace('"', '\"')
text = text.replace(''', '\'')
text = text.replace('>', '>')
text = text.replace('<', '<')
text = text.replace('&', '&')
return text
提交结果如下: