Skip to content

Commit

Permalink
Add problem 0482: License Key Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 8, 2024
1 parent abd2eff commit 05ad0a9
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/problem_0482_license_key_formatting/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
pub struct Solution;

impl Solution {
pub fn license_key_formatting(s: String, k: i32) -> String {
let k = k as usize;
let s = s
.chars()
.filter(|&x| (x != '-'))
.map(|x| x.to_ascii_uppercase())
.collect::<String>();
s.as_bytes()
.rchunks(k)
.rev()
.map(|x| String::from_utf8_lossy(x))
.collect::<Vec<_>>()
.join("-")
}
}

impl super::Solution for Solution {
fn license_key_formatting(s: String, k: i32) -> String {
Self::license_key_formatting(s, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
22 changes: 22 additions & 0 deletions src/problem_0482_license_key_formatting/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod iterative;

pub trait Solution {
fn license_key_formatting(s: String, k: i32) -> String;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(("5F3Z-2e-9-w", 4), "5F3Z-2E9W"),
(("2-5g-3-J", 2), "2-5G-3J"),
(("---", 3), ""),
];

for ((s, k), expected) in test_cases {
assert_eq!(S::license_key_formatting(s.to_string(), k), expected);
}
}
}

0 comments on commit 05ad0a9

Please sign in to comment.