leetcode: solve problem 17

This commit is contained in:
Ivan R. 2024-02-08 17:47:09 +05:00
parent b2e06356b0
commit 90b7316078
Signed by: lumin
GPG key ID: 927D3132247BDE4E
4 changed files with 83 additions and 0 deletions

View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "letter-combinations-of-a-phone-number"
version = "0.1.0"

View file

@ -0,0 +1,8 @@
[package]
name = "letter-combinations-of-a-phone-number"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View file

@ -0,0 +1,8 @@
# 17. Letter Combinations of a Phone Number
[Leetcode](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/)
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

View file

@ -0,0 +1,60 @@
pub fn letter_combinations(digits: String) -> Vec<String> {
let mut res: Vec<String> = vec![];
for digit in digits.split("") {
if digit.is_empty() {
continue;
}
let letters = match digit {
"2" => vec!["a", "b", "c"],
"3" => vec!["d", "e", "f"],
"4" => vec!["g", "h", "i"],
"5" => vec!["j", "k", "l"],
"6" => vec!["m", "n", "o"],
"7" => vec!["p", "q", "r", "s"],
"8" => vec!["t", "u", "v"],
"9" => vec!["w", "x", "y", "z"],
&_ => vec![],
};
if res.is_empty() {
for letter in letters {
res.push(letter.to_owned());
}
continue;
}
let mut mu: Vec<String> = vec![];
for el in res.iter() {
for letter in &letters {
mu.push(el.to_owned() + letter);
}
}
res = mu;
}
res
}
#[cfg(test)]
mod tests {
use super::letter_combinations;
#[test]
fn simple_test() {
let expected: Vec<String> = vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
.iter()
.map(|s| s.to_string())
.collect();
let res = letter_combinations("23".to_string());
assert_eq!(res, expected);
}
#[test]
fn test_empty_string() {
let expected: Vec<String> = vec![];
let res = letter_combinations("".to_string());
assert_eq!(res, expected);
}
}