Skip to content

Commit 02bb15f

Browse files
committed
Add problem 2138: Divide a String Into Groups of Size k
1 parent 4db1098 commit 02bb15f

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,7 @@ pub mod problem_1961_check_if_string_is_a_prefix_of_array;
639639
pub mod problem_1962_remove_stones_to_minimize_the_total;
640640
pub mod problem_2032_two_out_of_three;
641641
pub mod problem_2108_find_first_palindromic_string_in_the_array;
642+
pub mod problem_2138_divide_a_string_into_groups_of_size_k;
642643
pub mod problem_2348_number_of_zero_filled_subarrays;
643644

644645
#[cfg(test)]
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
pub struct Solution;
2+
3+
impl Solution {
4+
pub fn divide_string(s: String, k: i32, fill: char) -> Vec<String> {
5+
let mut result = vec![];
6+
let extra = (k - (s.len() as i32 % k)) as usize;
7+
let s = s.into_bytes();
8+
for bytes in s.chunks(k as usize) {
9+
let mut bytes = bytes.to_vec();
10+
if bytes.len() != k as usize {
11+
bytes.extend(std::iter::repeat_n(fill as u8, extra));
12+
}
13+
result.push(String::from_utf8(bytes).unwrap());
14+
}
15+
result
16+
}
17+
}
18+
19+
impl super::Solution for Solution {
20+
fn divide_string(s: String, k: i32, fill: char) -> Vec<String> {
21+
Self::divide_string(s, k, fill)
22+
}
23+
}
24+
25+
#[cfg(test)]
26+
mod tests {
27+
#[test]
28+
fn test_solution() {
29+
super::super::tests::run::<super::Solution>();
30+
}
31+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn divide_string(s: String, k: i32, fill: char) -> Vec<String>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
(("abcdefghi", 3, 'x'), &["abc", "def", "ghi"] as &[_]),
14+
(("abcdefghij", 3, 'x'), &["abc", "def", "ghi", "jxx"]),
15+
];
16+
17+
for ((s, k, fill), expected) in test_cases {
18+
assert_eq!(S::divide_string(s.to_string(), k, fill), expected);
19+
}
20+
}
21+
}

0 commit comments

Comments
 (0)