Skip to content

Commit

Permalink
Add problem 1417: Reformat The String
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Dec 11, 2024
1 parent 06f01e6 commit 5d9a84f
Show file tree
Hide file tree
Showing 3 changed files with 91 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 @@ -549,6 +549,7 @@ pub mod problem_1387_sort_integers_by_the_power_value;
pub mod problem_1390_four_divisors;
pub mod problem_1396_design_underground_system;
pub mod problem_1405_longest_happy_string;
pub mod problem_1417_reformat_the_string;
pub mod problem_1418_display_table_of_food_orders_in_a_restaurant;
pub mod problem_1433_check_if_a_string_can_break_another_string;
pub mod problem_1441_build_an_array_with_stack_operations;
Expand Down
48 changes: 48 additions & 0 deletions src/problem_1417_reformat_the_string/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
pub struct Solution;

impl Solution {
pub fn reformat(s: String) -> String {
let mut letter = vec![];
let mut digit = vec![];
for ch in s.chars() {
if ch.is_numeric() {
digit.push(ch);
} else {
letter.push(ch);
}
}
if letter.len().abs_diff(digit.len()) > 1 {
return String::new();
}
let mut result = String::with_capacity(s.len());

let (a, mut b) = if letter.len() > digit.len() {
(letter.into_iter(), digit.into_iter())
} else {
(digit.into_iter(), letter.into_iter())
};

for ch in a {
result.push(ch);
if let Some(ch) = b.next() {
result.push(ch);
}
}

result
}
}

impl super::Solution for Solution {
fn reformat(s: String) -> String {
Self::reformat(s)
}
}

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

pub trait Solution {
fn reformat(s: String) -> String;
}

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

pub fn run<S: Solution>() {
let test_cases = [
("a0b1c2", true),
("leetcode", false),
("1229857369", false),
("covid2019", true),
];

for (s, expected) in test_cases {
let result = S::reformat(s.to_string());

if expected {
assert_eq!(
test_utilities::unstable_sorted(result.bytes()),
test_utilities::unstable_sorted(s.bytes()),
);

let mut iter = result.bytes().map(|c| c.is_ascii_digit());
let mut prev = iter.next().unwrap();

for value in iter {
assert_ne!(value, prev);

prev = value;
}
} else {
assert!(result.is_empty());
}
}
}
}

0 comments on commit 5d9a84f

Please sign in to comment.