Simple Java Solution


  • 0
    X

    The trick is to use
    x / 2 * 2 to ignore the extra 1 case

    public int longestPalindrome(String s) {
            int length = s.length();
            if (length == 0) {
                return 0;
            }
            
            int[] table = new int[256];
            
            for (char c : s.toCharArray()) {
                table[c] ++;
            }
            
            int result = 0;
            int countOdd = 0;
            for (int i : table) {
                if (i % 2 == 1) {
                    countOdd = 1;
                }
                result += i / 2 * 2;
            }
            
            return countOdd + result;
        }
    

Log in to reply
 

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