Simple int array solution Java (5 lines)


  • 2
    L

    Count characters as ints (52 in total, but 6 ASCII characters between 'Z' and 'a' so we use 58 in total for easy indexing), then add to longest palindrome length based on whether there is an even or odd count of a character. In the end we add 1 to our longest palindrome length if one character has an odd count (determined based off whether our total count is less than the string length).

    public int longestPalindrome(String s) {
          int[] letters = new int[58];
          int longest = 0;
          for (char c : s.toCharArray()) letters[c - 'A']++;
          for (int l : letters) longest += l % 2 == 0 ? l : l - 1;
          return longest < s.length() ? longest + 1 : longest;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.