From 12d1ae53960b06698006b83a1b6832e8bc1d486a Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Fri, 17 Feb 2023 19:16:35 +0800 Subject: [PATCH] =?UTF-8?q?Update=200093.=E5=A4=8D=E5=8E=9FIP=E5=9C=B0?= =?UTF-8?q?=E5=9D=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `&Vec` 内部实现包括指向堆上分配的缓冲区的指针、容量和长度信息等,在这里我们不需要那么多没用的信息,这可以减少一部分开销 --- problems/0093.复原IP地址.md | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index a825b815..1f99a7a5 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -566,14 +566,24 @@ function restoreIpAddresses(s: string): string[] { ```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; } + fn is_valid(s: &[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; } + for &c in s.iter().take(end + 1).skip(start) { + if !('0'..='9').contains(&c) { + return false; + } + if let Some(digit) = c.to_digit(10) { + num = num * 10 + digit; + } + if num > 255 { + return false; + } } true }