Java (10 ms, beats 90%, easy to understand)


  • 0
    public class Solution {
        public int longestPalindrome(String s) {
            int[] asc = new int[256];
            char[] array = s.toCharArray();
            int len = 0;
            int temOddMax = 0;
            int mark = 0; // judge if asc[] exists odd number of letters
            //map the array and the count of each letter into asc[]
            for (int i = 0; i < array.length; i++) {
                asc[array[i]]++;
            }
            
            for (int i = 0; i < 256; i++) {
               //if one letter's count is even, it must involve into the palindrome.
                if (asc[i] % 2 == 0) {
                    len += asc[i];
                // if one letter's count is odd, its even-count parts must involove the palindrome.
                } else {
                    mark = 1;  // mark asc[] exists odd count of letters
                    len += asc[i] - 1;
                }
            }
            if (mark == 1) {
                len = len + 1;
            }
            return len;
        }
    }
    

Log in to reply
 

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