题目
题解思路
c++中
//注释为该行内容不显示
/* */ 为这部分内容不显示
定义标记为flag 当遇到"/"时, 代表有注释内容
- 若后面紧跟着"/",则直接退出循环
- 若后面跟着"*", 则寻找注释结尾
代码
C++
class Solution {
public:
vector<string> removeComments(vector<string>& source) {
int n = source.size();
vector<string> res;
string temp = "";
bool flag = false;
for(auto &word : source){
for(int i = 0; i < word.size(); ++i){
if (flag){
if (i + 1 < word.size() && word[i] == '*' && word[i + 1] == '/'){
flag = false;
++i;
}
}else{
if (i + 1 < word.size() && word[i] == '/' && word[i + 1] == '*'){
flag = true;
++i;
}else if(i + 1 < word.size() && word[i] == '/' && word[i + 1] == '/'){
break;
}else{
temp += word[i];
}
}
}
if( !flag && temp != "") {
res.push_back(temp);
temp = "";
}
}
return res;
}
};
Python
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
res = []
temp = []
flag = False
for word in source:
i = 0
while i < len(word):
if flag:
while i + 1< len(word) and word[i] == '*' and word[i + 1] == "/":
flag = False
i += 1
else:
if i + 1 < len(word) and word[i] == '/' and word[i + 1] == "*":
flag = True
i += 1
elif i + 1 < len(word) and word[i] == '/' and word[i + 1] == '/':
break
else:
temp.append(word[i])
i += 1
if not flag and len(temp) > 0:
res.append("".join(temp))
temp = []
return res