File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ public int longestPalindrome (String s ) {
4
+ // Map to store frequency of occurrence of each character
5
+ Map <Character , Integer > frequencyMap = new HashMap <>();
6
+ // Count frequencies
7
+ for (char c : s .toCharArray ()) {
8
+ frequencyMap .put (c , frequencyMap .getOrDefault (c , 0 ) + 1 );
9
+ }
10
+
11
+ int res = 0 ;
12
+ boolean hasOddFrequency = false ;
13
+ for (int freq : frequencyMap .values ()) {
14
+ // Check is the frequency is even
15
+ if ((freq % 2 ) == 0 ) {
16
+ res += freq ;
17
+ } else {
18
+ // If the frequency is odd, one occurrence of the
19
+ // character will remain without a match
20
+ res += freq - 1 ;
21
+ hasOddFrequency = true ;
22
+ }
23
+ }
24
+ // If hasOddFrequency is true, we have at least one unmatched
25
+ // character to make the center of an odd length palindrome.
26
+ if (hasOddFrequency ) return res + 1 ;
27
+
28
+ return res ;
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments