409. Longest Palindrome#

Intuition

../../_images/409-Longest-Palindrome-Set-Intuition.png

Source: Yao Frankie

 1public int longestPalindrome(String s) {
 2  Set<Character> set = new HashSet<>();
 3  int pairsCount = 0;
 4
 5  for (char c : s.toCharArray()) {
 6    if (set.remove(c)) {
 7      // if character exists remove and add to pairsCount
 8      pairsCount++;
 9    } else {
10      set.add(c);
11    }
12  }
13
14  return (pairsCount * 2) + (set.isEmpty() ? 0 : 1);
15}