Skip to content

Commit

Permalink
Add problem 1754: Largest Merge Of Two Strings
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 8, 2024
1 parent bd7ac8f commit e111817
Show file tree
Hide file tree
Showing 3 changed files with 76 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 @@ -1308,6 +1308,7 @@ 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_1754_largest_merge_of_two_strings;
pub mod problem_1758_minimum_changes_to_make_alternating_binary_string;
pub mod problem_1759_count_number_of_homogenous_substrings;
pub mod problem_1760_minimum_limit_of_balls_in_a_bag;
Expand Down
54 changes: 54 additions & 0 deletions src/problem_1754_largest_merge_of_two_strings/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
pub struct Solution;

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

impl Solution {
pub fn largest_merge(word1: String, word2: String) -> String {
let mut iter_1 = word1.as_bytes().iter();
let mut iter_2 = word2.as_bytes().iter();
let mut c1 = *iter_1.next().unwrap();
let mut result = Vec::with_capacity(word1.len() + word2.len());

'outer: while let Some(&c2) = iter_2.next() {
loop {
if (c2, iter_2.as_slice()) > (c1, iter_1.as_slice()) {
result.push(c2);

break;
}

result.push(c1);

if let Some(&next_c1) = iter_1.next() {
c1 = next_c1;
} else {
c1 = c2;
iter_1 = iter_2;

break 'outer;
}
}
}

result.push(c1);
result.extend(iter_1);

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

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

impl super::Solution for Solution {
fn largest_merge(word1: String, word2: String) -> String {
Self::largest_merge(word1, word2)
}
}

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

pub trait Solution {
fn largest_merge(word1: String, word2: String) -> String;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(("cabaa", "bcaaa"), "cbcabaaaaa"),
(("abcabc", "abdcaba"), "abdcabcabcaba"),
];

for ((word1, word2), expected) in test_cases {
assert_eq!(S::largest_merge(word1.to_string(), word2.to_string()), expected);
}
}
}

0 comments on commit e111817

Please sign in to comment.