-
Notifications
You must be signed in to change notification settings - Fork 2
/
remove-comments.rs
60 lines (52 loc) · 1.69 KB
/
remove-comments.rs
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
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
impl Solution {
pub fn remove_comments(source: Vec<String>) -> Vec<String> {
enum Type {
/// 没有注释
NoComment,
/// 块注释
Comment1,
/// 行注释
Comment2,
}
let mut s = vec![];
let mut new_line = Vec::new();
let mut t = Type::NoComment;
for old_line in source {
let mut i = 0;
while i < old_line.len() {
match t {
Type::NoComment => {
if old_line[i..].starts_with("/*") {
t = Type::Comment1;
i += 1;
} else if old_line[i..].starts_with("//") {
t = Type::Comment2;
i += 1;
} else {
new_line.push(old_line.as_bytes()[i]);
}
}
Type::Comment1 => {
if old_line[i..].starts_with("*/") {
i += 1;
t = Type::NoComment;
}
}
Type::Comment2 => {
t = Type::NoComment;
break;
}
}
i += 1;
}
if !matches!(t, Type::Comment1) && !new_line.is_empty() {
s.push(unsafe { String::from_utf8_unchecked(new_line) });
new_line = Vec::new();
}
}
s
}
}