-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0722_removeComments.cc
74 lines (69 loc) · 1.55 KB
/
Problem_0722_removeComments.cc
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
#include <iostream>
#include <string>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
vector<string> removeComments(vector<string> &source)
{
vector<string> ans;
string new_ine;
bool inBlock = false;
for (auto &line : source)
{
for (int i = 0; i < line.size(); i++)
{
if (inBlock)
{
// 在注释块 /**/ 内
if (i + 1 < line.size() && line[i] == '*' && line[i + 1] == '/')
{
inBlock = false;
i++;
}
}
else
{
if (i + 1 < line.size() && line[i] == '/' && line[i + 1] == '*')
{
inBlock = true;
i++;
}
else if (i + 1 < line.size() && line[i] == '/' && line[i + 1] == '/')
{
// 在注释行 // ,全是注释
break;
}
else
{
// 非注释
new_ine += line[i];
}
}
}
if (!inBlock && new_ine != "")
{
ans.push_back(new_ine);
new_ine = "";
}
}
return ans;
}
};
void test()
{
Solution s;
vector<string> s1 = {
"/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ",
" testing */", "a = b + c;", "}"};
vector<string> o1 = {"int main()", "{ ", " ", "int a, b, c;", "a = b + c;", "}"};
EXPECT_TRUE(o1 == s.removeComments(s1));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}