Skip to content

Commit

Permalink
Add problem 2131: Longest Palindrome by Concatenating Two Letter Words
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 18, 2024
1 parent 68a0b52 commit f1856bf
Show file tree
Hide file tree
Showing 3 changed files with 86 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 @@ -1526,6 +1526,7 @@ pub mod problem_2119_a_number_after_a_double_reversal;
pub mod problem_2124_check_if_all_as_appears_before_all_bs;
pub mod problem_2129_capitalize_the_title;
pub mod problem_2130_maximum_twin_sum_of_a_linked_list;
pub mod problem_2131_longest_palindrome_by_concatenating_two_letter_words;
pub mod problem_2133_check_if_every_row_and_column_contains_all_numbers;
pub mod problem_2134_minimum_swaps_to_group_all_1s_together_ii;
pub mod problem_2138_divide_a_string_into_groups_of_size_k;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
pub struct Solution;

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

impl Solution {
pub fn longest_palindrome(words: Vec<String>) -> i32 {
let mut counts = [0_u32; 676];
let mut result = 0_u32;
let mut unpaired = 0_u32;

for word in words {
let [c0, c1]: [_; 2] = word.into_bytes().try_into().ok().unwrap();
let (c0, c1) = (u16::from(c0 - b'a'), u16::from(c1 - b'a'));

if c0 == c1 {
let count = &mut counts[usize::from(26 * c0 + c1)];

if *count == 0 {
unpaired += 1;
*count += 1;
} else {
unpaired -= 1;
*count -= 1;
result += 4;
}
} else {
let other_count = &mut counts[usize::from(26 * c1 + c0)];

if *other_count == 0 {
counts[usize::from(26 * c0 + c1)] += 1;
} else {
*other_count -= 1;
result += 4;
}
}
}

if unpaired != 0 {
result += 2;
}

result as _
}
}

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

impl super::Solution for Solution {
fn longest_palindrome(words: Vec<String>) -> i32 {
Self::longest_palindrome(words)
}
}

#[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,25 @@
pub mod greedy;

pub trait Solution {
fn longest_palindrome(words: Vec<String>) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(&["lc", "cl", "gg"] as &[_], 6),
(&["ab", "ty", "yt", "lc", "cl", "ab"], 8),
(&["cc", "ll", "xx"], 2),
];

for (words, expected) in test_cases {
assert_eq!(
S::longest_palindrome(words.iter().copied().map(str::to_string).collect()),
expected,
);
}
}
}

0 comments on commit f1856bf

Please sign in to comment.