Skip to content

Commit 25be777

Browse files
authored
Merge pull request #60 from tony84727/leetcode/91
feat: leetcode/91
2 parents 90cf887 + 677ab0a commit 25be777

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

src/leetcode/algorithm_91/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Decode Ways
2+
===========
3+
[leetcode](https://leetcode.com/problems/decode-ways/)

src/leetcode/algorithm_91/first.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
pub struct Solution;
2+
3+
impl Solution {
4+
pub fn num_decodings(s: String) -> i32 {
5+
if s.is_empty() {
6+
return 0;
7+
}
8+
let mut previous = 1;
9+
let mut ways = 1;
10+
let digits = s.into_bytes();
11+
let mut digits = digits.iter().map(|c| c - 0x30);
12+
let mut last = digits.next().unwrap();
13+
if last == 0 {
14+
return 0;
15+
}
16+
for d in digits {
17+
if d == 0 {
18+
if last > 0 && last <= 2 {
19+
ways = previous;
20+
} else {
21+
return 0;
22+
}
23+
} else {
24+
let temp = ways;
25+
if last > 0 && last * 10 + d <= 26 {
26+
ways += previous;
27+
}
28+
previous = temp;
29+
}
30+
last = d;
31+
}
32+
ways
33+
}
34+
}

src/leetcode/algorithm_91/mod.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
pub mod first;
2+
3+
#[cfg(test)]
4+
mod tests {
5+
use super::*;
6+
use test_case::test_case;
7+
8+
#[test_case("12" => 2; "example 1")]
9+
#[test_case("06" => 0; "case 1")]
10+
#[test_case("0" => 0; "case 2")]
11+
#[test_case("10" => 1; "case 3")]
12+
#[test_case("2101" => 1; "case 4")]
13+
#[test_case("1123" => 5; "case 5")]
14+
#[test_case("112" => 3; "case 6")]
15+
#[test_case("123123" => 9; "case 7")]
16+
#[test_case("2611055971756562" => 4; "case 8")]
17+
#[test_case("26110" => 2; "case 9")]
18+
#[test_case("2611" => 4; "case 10")]
19+
#[test_case("12120" => 3; "case 11")]
20+
fn test_first_solution(s: &str) -> i32 {
21+
first::Solution::num_decodings(s.to_string())
22+
}
23+
}

src/leetcode/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod algorithm_91;
12
pub mod algorithm_76;
23
pub mod algorithm_79;
34
pub mod algorithm_73;

0 commit comments

Comments
 (0)