Skip to content

feat: leetcode/91 #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/leetcode/algorithm_91/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Decode Ways
===========
[leetcode](https://leetcode.com/problems/decode-ways/)
34 changes: 34 additions & 0 deletions src/leetcode/algorithm_91/first.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
pub struct Solution;

impl Solution {
pub fn num_decodings(s: String) -> i32 {
if s.is_empty() {
return 0;
}
let mut previous = 1;
let mut ways = 1;
let digits = s.into_bytes();
let mut digits = digits.iter().map(|c| c - 0x30);
let mut last = digits.next().unwrap();
if last == 0 {
return 0;
}
for d in digits {
if d == 0 {
if last > 0 && last <= 2 {
ways = previous;
} else {
return 0;
}
} else {
let temp = ways;
if last > 0 && last * 10 + d <= 26 {
ways += previous;
}
previous = temp;
}
last = d;
}
ways
}
}
23 changes: 23 additions & 0 deletions src/leetcode/algorithm_91/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod first;

#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;

#[test_case("12" => 2; "example 1")]
#[test_case("06" => 0; "case 1")]
#[test_case("0" => 0; "case 2")]
#[test_case("10" => 1; "case 3")]
#[test_case("2101" => 1; "case 4")]
#[test_case("1123" => 5; "case 5")]
#[test_case("112" => 3; "case 6")]
#[test_case("123123" => 9; "case 7")]
#[test_case("2611055971756562" => 4; "case 8")]
#[test_case("26110" => 2; "case 9")]
#[test_case("2611" => 4; "case 10")]
#[test_case("12120" => 3; "case 11")]
fn test_first_solution(s: &str) -> i32 {
first::Solution::num_decodings(s.to_string())
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod algorithm_91;
pub mod algorithm_76;
pub mod algorithm_79;
pub mod algorithm_73;
Expand Down