mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
update 0017.电话号码的字母组合.md about rust 优化
This commit is contained in:
@ -450,42 +450,31 @@ function letterCombinations(digits: string): string[] {
|
|||||||
## Rust
|
## Rust
|
||||||
|
|
||||||
```Rust
|
```Rust
|
||||||
|
const map: [&str; 10] = [
|
||||||
|
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz",
|
||||||
|
];
|
||||||
impl Solution {
|
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();
|
let len = digits.len();
|
||||||
if len == index {
|
if len == index {
|
||||||
result.push(s.to_string());
|
result.push(s.to_string());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 在保证不会越界的情况下使用unwrap()将Some()中的值提取出来
|
let digit = (digits.as_bytes()[index] - b'0') as usize;
|
||||||
let digit= digits.chars().nth(index).unwrap().to_digit(10).unwrap() as usize;
|
for i in map[digit].chars() {
|
||||||
let letters = map[digit];
|
|
||||||
for i in letters.chars() {
|
|
||||||
s.push(i);
|
s.push(i);
|
||||||
Self::backtracking(result, s, &map, &digits, index+1);
|
Self::back_trace(result, s, digits, index + 1);
|
||||||
s.pop();
|
s.pop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn letter_combinations(digits: String) -> Vec<String> {
|
pub fn letter_combinations(digits: String) -> Vec<String> {
|
||||||
if digits.len() == 0 {
|
if digits.is_empty() {
|
||||||
return vec![];
|
return vec![];
|
||||||
}
|
}
|
||||||
const MAP: [&str; 10] = [
|
let mut res = vec![];
|
||||||
"",
|
let mut s = String::new();
|
||||||
"",
|
Self::back_trace(&mut res, &mut s, &digits, 0);
|
||||||
"abc",
|
res
|
||||||
"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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user