diff --git a/src/lib.rs b/src/lib.rs index 2d5c05d..fa37bd6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,4 +28,5 @@ pub mod remove_duplicates_from_sorted_array; pub mod add_strings; pub mod flip_and_invert_image; pub mod leaf_similar; -pub mod sum_of_left_leaves; \ No newline at end of file +pub mod sum_of_left_leaves; +pub mod license_key_formatting; \ No newline at end of file diff --git a/src/license_key_formatting.rs b/src/license_key_formatting.rs new file mode 100644 index 0000000..32559e6 --- /dev/null +++ b/src/license_key_formatting.rs @@ -0,0 +1,29 @@ +pub fn license_key_formatting(s: String, k: i32) -> String { + let s = s.to_uppercase().replace('-', ""); + let mut result = String::new(); + let mut cur = s.as_str(); + while !cur.is_empty() { + let (chunk, rest) = + cur.split_at(std::cmp::max(0, cur.len() as isize - k as isize) as usize); + if result.is_empty() { + rest.clone_into(&mut result); + } else { + result = format!("{}-{}", rest, result); + } + cur = chunk; + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!( + license_key_formatting("5F3Z-2e-9-w".to_owned(), 4), + "5F3Z-2E9W" + ); + } +}