We know that palindrome can be even length or odd length. For even length, we can all the frequency of chars are even. For odd length, we central char with freq odd, but rest of the chars have frequency even.
We can add chars to hashset.
When we see the char for 2nd time, we will remove it from the set.
In the end only odd frequencies will remain in hashset
classSolution {
publicintlongestPalindrome(String s) {
if (s ==null|| s.length() == 0) {
return 0;
}
Set<Character> hs =new HashSet<Character>();
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (hs.contains(s.charAt(i))) {
hs.remove(s.charAt(i));
count++;
} else {
hs.add(s.charAt(i));
}
}
if (!hs.isEmpty()) {
return count * 2 + 1;
}
return count * 2;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintlongestPalindrome(String s) {
Set<Character> set =new HashSet<>();
int n = s.length();
for (int i = 0; i < n; i++) {
if (!set.add(s.charAt(i))) {
set.remove(s.charAt(i));
}
}
return set.size() <= 1 ? n : n - set.size() + 1;
}
}