2744. Find Maximum Number of String Pairs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public int maximumNumberOfStringPairs(String[] words) {
int pairs = 0;

Set<String> set = new HashSet<>();
for (String word : words) {
String reversedWord = reverse(word);
if (set.contains(reversedWord)) {
set.remove(reversedWord);
pairs++;
} else {
set.add(word);
}
}

return pairs;
}

private String reverse(String word) {
char[] chars = word.toCharArray();
int i = 0, j = chars.length - 1;
while (i++ < j--) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}

return new String(chars);
}
}

References

2744. Find Maximum Number of String Pairs