Skip to content

Commit

Permalink
Add problem 1957: Delete Characters to Make Fancy String
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 15, 2023
1 parent 36214ff commit 66b8398
Show file tree
Hide file tree
Showing 3 changed files with 71 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 @@ -1478,6 +1478,7 @@ pub mod problem_1935_maximum_number_of_words_you_can_type;
pub mod problem_1941_check_if_all_characters_have_equal_number_of_occurrences;
pub mod problem_1945_sum_of_digits_of_string_after_convert;
pub mod problem_1952_three_divisors;
pub mod problem_1957_delete_characters_to_make_fancy_string;

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

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

impl Solution {
pub fn make_fancy_string(s: String) -> String {
let mut s = s.into_bytes();
let slice = s.as_mut_slice();
let mut writer = 0;
let mut i = 0;
let mut prev = 0;
let mut count = 0_u8;

while let Some(&c) = slice.get(i) {
i += 1;

if c == prev {
if count < 2 {
count += 1;
} else {
continue;
}
} else {
prev = c;
count = 1;
}

slice[writer] = c;
writer += 1;
}

s.truncate(writer);

String::from_utf8(s).unwrap()
}
}

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

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

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

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

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

pub fn run<S: Solution>() {
let test_cases = [("leeetcode", "leetcode"), ("aaabaaaa", "aabaa"), ("aab", "aab")];

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

0 comments on commit 66b8398

Please sign in to comment.