Skip to content

Commit

Permalink
Add problem 2138: Divide a String Into Groups of Size k
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Feb 22, 2024
1 parent f045dc5 commit 1e044c3
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1455,6 +1455,7 @@ pub mod problem_2124_check_if_all_as_appears_before_all_bs;
pub mod problem_2129_capitalize_the_title;
pub mod problem_2130_maximum_twin_sum_of_a_linked_list;
pub mod problem_2134_minimum_swaps_to_group_all_1s_together_ii;
pub mod problem_2138_divide_a_string_into_groups_of_size_k;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::iter;

impl Solution {
pub fn divide_string(s: String, k: i32, fill: char) -> Vec<String> {
let n = s.len();
let k = k as u32 as usize;
let mut prev = 0;
let mut result = Vec::with_capacity(s.len().div_ceil(k));

while let Some(s) = s.get(prev..prev + k) {
result.push(s.to_string());

prev += k;
}

if n != prev {
let mut group = s[prev..].to_string();

group.extend(iter::repeat(fill).take(k - (n - prev)));

result.push(group);
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn divide_string(s: String, k: i32, fill: char) -> Vec<String> {
Self::divide_string(s, k, fill)
}
}

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

pub trait Solution {
fn divide_string(s: String, k: i32, fill: char) -> Vec<String>;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(("abcdefghi", 3, 'x'), &["abc", "def", "ghi"] as &[_]),
(("abcdefghij", 3, 'x'), &["abc", "def", "ghi", "jxx"]),
];

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

0 comments on commit 1e044c3

Please sign in to comment.