-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrestore-ip-addresses.rs
62 lines (52 loc) · 1.57 KB
/
restore-ip-addresses.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
61
62
#![allow(dead_code, unused, unused_variables)]
fn main() {
println!(
"{:?}",
Solution::restore_ip_addresses(String::from("25525511135"))
);
println!("{:?}", Solution::restore_ip_addresses(String::from("0000")));
println!(
"{:?}",
Solution::restore_ip_addresses(String::from("010010"))
);
println!("{:?}", Solution::restore_ip_addresses(String::from("1111")));
println!(
"{:?}",
Solution::restore_ip_addresses(String::from("0279245587303"))
);
}
struct Solution;
impl Solution {
pub fn restore_ip_addresses(s: String) -> Vec<String> {
Self::ip(&s, 4)
}
fn ip(s: &str, level: i32) -> Vec<String> {
let mut result = vec![];
if s.len() < level as usize {
return result;
}
if level == 1 {
// 这里故意设置为256,使得数字大于255,为true
return if (s.starts_with('0') && s.len() > 1) || s.parse::<i32>().unwrap_or(256) > 255 {
result
} else {
vec![String::from(s)]
};
}
for i in 0..3 {
if s.len() > i {
if i == 2 && s[..3].parse::<i32>().unwrap_or(256) > 255 {
return result;
}
let r = Self::ip(&s[i + 1..], level - 1);
for j in r {
result.push(format!("{}.{}", &s[0..=i], j));
}
if s.starts_with('0') {
return result;
}
}
}
result
}
}