forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-comments.cpp
30 lines (29 loc) · 1.04 KB
/
remove-comments.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Time: O(n), n is the length of the source
// Space: O(k), k is the max length of a line
class Solution {
public:
vector<string> removeComments(vector<string>& source) {
bool in_block = false;
vector<string> result;
string newline;
for (const auto& line : source) {
for (int i = 0; i < line.length(); ++i) {
if (!in_block && i + 1 < line.length() && line.substr(i, 2) == "/*") {
in_block = true;
++i;
} else if (in_block && i + 1 < line.length() && line.substr(i, 2) == "*/") {
in_block = false;
++i;
} else if (!in_block && i + 1 < line.length() && line.substr(i, 2) == "//") {
break;
} else if (!in_block) {
newline.push_back(line[i]);
}
}
if (!in_block && !newline.empty()) {
result.emplace_back(move(newline));
}
}
return result;
}
};