Skip to content

Commit 48b57cb

Browse files
committed
Runtime: 0 ms (Top 100.0%) | Memory: 8.10 MB (Top 52.2%)
1 parent 5135b21 commit 48b57cb

File tree

1 file changed

+32
-33
lines changed

1 file changed

+32
-33
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,39 @@
1+
// Runtime: 0 ms (Top 100.0%) | Memory: 8.10 MB (Top 52.2%)
2+
13
class Solution {
24
public:
3-
vector<string> removeComments(vector<string>& source) {
4-
bool commentStart = false;
5-
vector<string> res;
6-
7-
bool multiComment = false; // are we having a multi-line comment?
8-
for (string &eachS : source) {
9-
if (!multiComment) {
10-
res.emplace_back();
11-
}
12-
for (int i = 0; i < eachS.size(); i++) {
13-
if (!multiComment && eachS[i] == '/') {
14-
i++;
15-
if (eachS[i] == '/') {
16-
break;
17-
} else if (eachS[i] == '*') {
18-
multiComment = true;
19-
} else {
20-
res.back() += '/';
21-
res.back() += eachS[i];
22-
}
23-
} else if (multiComment && eachS[i] == '*') {
24-
if (i + 1 < eachS.size() && eachS[i + 1] == '/') {
25-
i++;
26-
multiComment = false;
27-
}
28-
} else {
29-
if (!multiComment) {
30-
res.back() += eachS[i];
31-
}
5+
vector<string> removeComments(vector<string>& source) {
6+
string cur="";
7+
vector<string> out;
8+
bool comm=false; // it will help us see whether comment is active or not
9+
10+
for(string s: source){
11+
for(int j=0; j<s.size(); j++){
12+
// that means a comment is started
13+
if(!comm && s[j]=='/' && s[j+1]=='*'){
14+
comm = true;
15+
j++;
16+
}
17+
// what if a // <- is present, then full line is not read & break
18+
// also make sure it is outside comments
19+
else if(!comm && s[j]=='/' && s[j+1]=='/') break;
20+
// check if a comment is completed
21+
else if(comm && s[j]=='*' && s[j+1]=='/') {
22+
comm=false;
23+
j++;
3224
}
25+
// or else it is a valid code
26+
else if (!comm)
27+
cur+=s[j];
28+
}
29+
// now check if it's a comment or not and its not blank (because comments
30+
// are blank lines) and add it to output
31+
32+
if(!comm && cur.size()){
33+
out.push_back(cur);
34+
cur="";
3335
}
34-
if (!multiComment && res.back().empty()) {
35-
res.pop_back();
36-
}
3736
}
38-
return res;
37+
return out;
3938
}
4039
};

0 commit comments

Comments
 (0)