-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindrome.java
More file actions
45 lines (29 loc) · 973 Bytes
/
Copy pathLongestPalindrome.java
File metadata and controls
45 lines (29 loc) · 973 Bytes
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package LeetcodePractice;
import java.util.HashMap;
import java.util.Map;
public class LongestPalindrome {
public static int longestPalindrome(String s) {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : s.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
int length = 0;
boolean hasOddCount = false;
for (int count : charCount.values()) {
length += (count / 2) * 2;
if (count % 2 == 1) {
hasOddCount = true;
}
}
if (hasOddCount) {
length += 1;
}
return length;
}
public static void main(String[] args) {
String s1 = "abccccdd";
String s2 = "a";
System.out.println("Input: " + s1 + " -> Output: " + longestPalindrome(s1));
System.out.println("Input: " + s2 + " -> Output: " + longestPalindrome(s2));
}
}