Skip to content

Commit

Permalink
Add problem 1750: Minimum Length of String After Deleting Similar Ends
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 3, 2024
1 parent c81344c commit 265a03d
Show file tree
Hide file tree
Showing 3 changed files with 89 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 @@ -1304,6 +1304,7 @@ pub mod problem_1743_restore_the_array_from_adjacent_pairs;
pub mod problem_1745_palindrome_partitioning_iv;
pub mod problem_1748_sum_of_unique_elements;
pub mod problem_1749_maximum_absolute_sum_of_any_subarray;
pub mod problem_1750_minimum_length_of_string_after_deleting_similar_ends;
pub mod problem_1752_check_if_array_is_sorted_and_rotated;
pub mod problem_1753_maximum_score_from_removing_stones;
pub mod problem_1758_minimum_changes_to_make_alternating_binary_string;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
pub struct Solution;

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

impl Solution {
pub fn minimum_length(s: String) -> i32 {
let mut iter = s.as_bytes().iter();
let mut first = iter.next().copied().unwrap();

if let Some(mut last) = iter.next_back().copied() {
loop {
if first == last {
// Consume left side that has the same value as `first`.

loop {
if let Some(&left) = iter.next() {
if left != first {
first = left;

break;
}
} else {
return 0;
}
}

// Consume right side that has the same value as `last`.

loop {
if let Some(&right) = iter.next_back() {
if right != last {
last = right;

break;
}
} else {
return 1;
}
}
} else {
return iter.len() as i32 + 2;
}
}
} else {
1
}
}
}

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

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

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pub mod iterative;

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

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

pub fn run<S: Solution>() {
let test_cases = [
("ca", 2),
("cabaabac", 0),
("aabccabba", 3),
("bbbbbbbbbbbbbbbbbbbbbbbbbbbabbbbbbbbbbbbbbbccbcbcbccbbabbb", 1),
("c", 1),
];

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

0 comments on commit 265a03d

Please sign in to comment.