Input: words =["cd","ac","dc","ca","zz"]Output: 2Explanation: In this example, we can form 2 pair of strings in the following way:- We pair the 0th string with the 2nd string, as the reversed string of word[0]is"dc" and is equal to words[2].- We pair the 1st string with the 3rd string, as the reversed string of word[1]is"ca" and is equal to words[3].It can be proven that 2is the maximum number of pairs that can be formed.
Input: words =["ab","ba","cc"]Output: 1Explanation: In this example, we can form 1 pair of strings in the following way:- We pair the 0th string with the 1st string, as the reversed string of words[1]is"ab" and is equal to words[0].It can be proven that 1is the maximum number of pairs that can be formed.
We want to pair each string with its reverse, but each string can be used at most once. By using a set to track available strings, we can efficiently check for reverse pairs.
classSolution {
publicintmaximumNumberOfStringPairs(String[] words) {
Set<String> st =new HashSet<>(Arrays.asList(words));
int ans = 0;
for (String w : words) {
String rev =new StringBuilder(w).reverse().toString();
if (st.contains(w) && st.contains(rev) &&!w.equals(rev)) {
ans++;
st.remove(w);
st.remove(rev);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmaximumNumberOfStringPairs(words: Array<String>): Int {
val st = words.toMutableSet()
var ans = 0for (w in words) {
val rev = w.reversed()
if (w != rev && w in st && rev in st) {
ans++ st.remove(w)
st.remove(rev)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaximumNumberOfStringPairs(self, words: list[str]) -> int:
st = set(words)
ans =0for w in words:
rev = w[::-1]
if w != rev and w in st and rev in st:
ans +=1 st.remove(w)
st.remove(rev)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmaximum_number_of_string_pairs(words: Vec<String>) -> i32 {
use std::collections::HashSet;
letmut st: HashSet<String>= words.iter().cloned().collect();
letmut ans =0;
for w in&words {
let rev: String = w.chars().rev().collect();
if w !=&rev && st.contains(w) && st.contains(&rev) {
ans +=1;
st.remove(w);
st.remove(&rev);
}
}
ans
}
}