From 26376b6417a102e883071452c9863982f1d77802 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sun, 17 Jul 2022 10:53:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200093.=E5=A4=8D=E5=8E=9FIP?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0093.复原IP地址 Rust版本 --- problems/0093.复原IP地址.md | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) 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 //记录结果