Skip to content

Commit 107bee3

Browse files
authored
Create remove-comments.cpp
1 parent ed9860f commit 107bee3

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/remove-comments.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n), n is the length of the source
2+
// Space: O(k), k is the max length of a line
3+
4+
class Solution {
5+
public:
6+
vector<string> removeComments(vector<string>& source) {
7+
bool in_block = false;
8+
vector<string> result;
9+
string newline;
10+
for (const auto& line : source) {
11+
for (int i = 0; i < line.length(); ++i) {
12+
if (!in_block && i + 1 < line.length() && line.substr(i, 2) == "/*") {
13+
in_block = true;
14+
++i;
15+
} else if (in_block && i + 1 < line.length() && line.substr(i, 2) == "*/") {
16+
in_block = false;
17+
++i;
18+
} else if (!in_block && i + 1 < line.length() && line.substr(i, 2) == "//") {
19+
break;
20+
} else if (!in_block) {
21+
newline.push_back(line[i]);
22+
}
23+
}
24+
if (!in_block && !newline.empty()) {
25+
result.emplace_back(move(newline));
26+
}
27+
}
28+
return result;
29+
}
30+
};

0 commit comments

Comments
 (0)