mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1527 from cezarbbb/Backtracking02
添加 0093.复原IP地址 Rust版本
This commit is contained in:
@ -536,6 +536,53 @@ func isNormalIp(s string,startIndex,end int)bool{
|
||||
|
||||
```
|
||||
|
||||
## Rust
|
||||
|
||||
```Rust
|
||||
impl Solution {
|
||||
fn is_valid(s: &Vec<char>, start: usize, end: usize) -> bool {
|
||||
if start > end { return false; }
|
||||
if s[start] == '0' && start != end { return false; }
|
||||
let mut num = 0;
|
||||
for i in start..=end {
|
||||
if s[i] > '9' || s[i] < '0' { return false; }
|
||||
if let Some(digit) = s[i].to_digit(10) { num = num * 10 + digit; }
|
||||
if num > 255 { return false; }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn backtracking(result: &mut Vec<String>, s: &mut Vec<char>, start_index: usize, mut point_num: usize) {
|
||||
let len = s.len();
|
||||
if point_num == 3 {
|
||||
if Self::is_valid(s, start_index, len - 1) {
|
||||
result.push(s.iter().collect::<String>());
|
||||
}
|
||||
return;
|
||||
}
|
||||
for i in start_index..len {
|
||||
if Self::is_valid(s, start_index, i) {
|
||||
point_num += 1;
|
||||
s.insert(i + 1, '.');
|
||||
Self::backtracking(result, s, i + 2, point_num);
|
||||
point_num -= 1;
|
||||
s.remove(i + 1);
|
||||
} else { break; }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn restore_ip_addresses(s: String) -> Vec<String> {
|
||||
let mut result: Vec<String> = Vec::new();
|
||||
let len = s.len();
|
||||
if len < 4 || len > 12 { return result; }
|
||||
let mut s = s.chars().collect::<Vec<char>>();
|
||||
Self::backtracking(&mut result, &mut s, 0, 0);
|
||||
result
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## C
|
||||
```c
|
||||
//记录结果
|
||||
|
Reference in New Issue
Block a user