Skip to content

Commit 2483e02

Browse files
authored
Create Longest Palindrome.java
1 parent ff6c771 commit 2483e02

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

String/Longest Palindrome.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

0 commit comments

Comments
 (0)