Longest Palindrome by Concatenating Two Letter Words LeetCode solution in Java

1
class Solution {
2
public int longestPalindrome(String[] words) {
3
int[][] freq = new int[26][26]; // array for all alphabet combinations
4
for (String word : words)
5
freq[word.charAt(0) - 'a'][
6
word.charAt(1) - 'a']++; // here we first increase the freq for every word
7
int left = 0; // to store freq counts
8
boolean odd = false;
9
for (int i = 0; i != 26; i++) { // iterate over our array
10
odd |= (freq[i][i] & 1) == 1; // means odd number of freq for similar words are there
11
left += freq[i][i] / 2;
12
for (int j = i + 1; j != 26; j++) // nested iteration to find non similar pairs
13
left += Math.min(freq[i][j], freq[j][i]); // taking min times from both present
14
}
15
int res = left * 2 * 2; // res from total freq found!!
16
if (odd) {
17
res += 2; // if odd then adding 2
18
}
19
return res;
20
}
21
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0