diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 11ca2d03..46ac1c86 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -536,6 +536,53 @@ func isNormalIp(s string,startIndex,end int)bool{ ``` +## Rust + +```Rust +impl Solution { + fn is_valid(s: &Vec, 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, s: &mut Vec, 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::()); + } + 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 { + let mut result: Vec = Vec::new(); + let len = s.len(); + if len < 4 || len > 12 { return result; } + let mut s = s.chars().collect::>(); + Self::backtracking(&mut result, &mut s, 0, 0); + result + } + +} +``` + ## C ```c //记录结果