From 6df0981377bece752ccba09c208751cd9ad87414 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+fwqaaq@users.noreply.github.com> Date: Sun, 18 Dec 2022 23:31:36 +0800 Subject: [PATCH] =?UTF-8?q?update=200017.=E7=94=B5=E8=AF=9D=E5=8F=B7?= =?UTF-8?q?=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88.md=20abo?= =?UTF-8?q?ut=20rust=20=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 35 +++++++------------- 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 12a45a61..a3ab112f 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -450,42 +450,31 @@ function letterCombinations(digits: string): string[] { ## Rust ```Rust +const map: [&str; 10] = [ + "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", +]; impl Solution { - fn backtracking(result: &mut Vec, s: &mut String, map: &[&str; 10], digits: &String, index: usize) { + fn back_trace(result: &mut Vec, s: &mut String, digits: &String, index: usize) { let len = digits.len(); if len == index { result.push(s.to_string()); return; } - // 在保证不会越界的情况下使用unwrap()将Some()中的值提取出来 - let digit= digits.chars().nth(index).unwrap().to_digit(10).unwrap() as usize; - let letters = map[digit]; - for i in letters.chars() { + let digit = (digits.as_bytes()[index] - b'0') as usize; + for i in map[digit].chars() { s.push(i); - Self::backtracking(result, s, &map, &digits, index+1); + Self::back_trace(result, s, digits, index + 1); s.pop(); } } pub fn letter_combinations(digits: String) -> Vec { - if digits.len() == 0 { + if digits.is_empty() { return vec![]; } - const MAP: [&str; 10] = [ - "", - "", - "abc", - "def", - "ghi", - "jkl", - "mno", - "pqrs", - "tuv", - "wxyz" - ]; - let mut result: Vec = Vec::new(); - let mut s: String = String::new(); - Self::backtracking(&mut result, &mut s, &MAP, &digits, 0); - result + let mut res = vec![]; + let mut s = String::new(); + Self::back_trace(&mut res, &mut s, &digits, 0); + res } } ```