-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-comments.cpp
74 lines (60 loc) · 1.31 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* Copyright (c) 2020 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> removeComments(vector<string> &source) {
vector<string> out;
string orphan;
bool in_block = false;
for (auto &s : source) {
size_t i = 0;
if (in_block) {
size_t pos2 = s.find("*/");
if (string::npos == pos2) {
continue;
}
s.erase(0, pos2 + 2);
s = orphan + s;
in_block = false;
i = orphan.size();
}
for (; i < s.size();) {
size_t pos = s.find("/", i);
if (pos == string::npos) {
break;
}
if (s[pos + 1] != '/' && s[pos + 1] != '*') {
i = pos + 2;
continue;
}
if (s[pos + 1] == '/') {
s.erase(pos);
break;
}
if (s[pos + 1] != '*') {
i = pos + 2;
continue;
}
size_t pos2 = s.find("*/", pos + 2);
if (string::npos == pos2) {
s.erase(pos);
orphan = s;
in_block = true;
break;
}
s.erase(pos, pos2 - pos + 2);
i = pos;
}
if (!s.empty() && !in_block) {
out.push_back(s);
}
}
return out;
}
};