没什么好说的,无语了。
python:没优化的
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
if not source:
return []
res = []
tmp_code = ''
block = False
skip = False
for code in source:
for i in range(len(code)):
if skip:
skip = False
continue
if i < len(code) - 1 and code[i] == "/" and code[i+1] == "/" and not block:
if tmp_code:
res.append(tmp_code)
tmp_code = ''
break
elif i < len(code) - 1 and code[i] == "/" and code[i+1] == "*" and not block:
block = True
skip = True
elif i < len(code) - 1 and code[i] == "*" and code[i+1] == "/" and block:
block = False
skip = True
else:
if block:
continue
else:
tmp_code += code[i]
if not block:
if len(tmp_code) > 0:
res.append(tmp_code)
tmp_code = ''
return res
C++:优化过的
class Solution {
public:
vector<string> removeComments(vector<string>& source) {
vector<string> res;
string tmp;
bool block = false;
for (auto& code : source) {
int m = code.size();
for (int i = 0; i < m; i++) {
if (block) {
if (i + 1 < m && code[i] == '*' && code[i + 1] == '/') {
block = false;
i++;
}
}
else {
if (i + 1 < m && code[i] == '/' && code[i + 1] == '*') {
block = true;
i++;
}
else if (i + 1 < m && code[i] == '/' && code[i + 1] == '/') {
break;
}
else {
tmp.push_back(code[i]);
}
}
}
if (!block && !tmp.empty()) {
res.push_back(tmp);
tmp.clear();
}
}
return res;
}
};