#2744
Easy Algorithms Find maximum number of string pairs
Array Hash Table String Simulation
82.3% acceptance
Feb 25, 2026
467
18
You are given a 0-indexed array words consisting of distinct strings.
The string words[i] can be paired with the string words[j] if:
The string words[i] is equal to the reversed string of words[j].
0 <= i < j < words.length.
Return the maximum number of pairs that can be formed from the array words.
Note that each string can belong in at most one pair.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn maximum_number_of_string_pairs(words: Vec<String>) -> i32 {
use std::collections::HashSet;
let mut seen: HashSet<String> = HashSet::new();
let mut count = 0;
for word in &words {
let rev: String = word.chars().rev().collect();
if seen.contains(&rev) {
count += 1;
seen.remove(&rev);
} else {
seen.insert(word.clone());
}
}
count
}
}