722. Remove Comments

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
class Solution {
public List<String> removeComments(String[] source) {
List<String> resultList = new ArrayList<>();

boolean inBlockComment = false;
StringBuilder sb = new StringBuilder(80);
for (String line : source) {
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);

if (inBlockComment) {
// 在块中的字符都不添加
// 在块中,希望搜索到 */
if (c == '*' && i + 1 < line.length() && line.charAt(i + 1) == '/') {
// 块结束
inBlockComment = false;
i++; // 移动至 / 字符
}
} else if (c == '/' && i + 1 < line.length()) {
char nextC = line.charAt(i + 1);
if (nextC == '/') {
break; // 处理下一行
} else if (nextC == '*') {
inBlockComment = true; // 进入块模式
i++; // 移动至 * 字符
// 持续搜索,直到块结尾
} else {
sb.append(c);
}
} else {
// 不在块中的字符都需要添加
sb.append(c);
}
}

if (sb.length() > 0 && !inBlockComment) {
resultList.add(sb.toString());
sb.setLength(0);
}
}

return resultList;
}
}

References

722. Remove Comments