mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
update 0017.电话号码的字母组合.md about rust 优化
This commit is contained in:
@ -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<String>, s: &mut String, map: &[&str; 10], digits: &String, index: usize) {
|
||||
fn back_trace(result: &mut Vec<String>, 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<String> {
|
||||
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<String> = 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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user