Space Improved Java Solution using Bitmap with Explanation


  • 0
    C
    public class Solution {
        public int longestPalindrome(String s) {
            if (s == null || s.length() == 0) return 0;
    //use long type for bitmap since 52 bits needed for total lowercase plus uppercase characters
            long checker = 0;
            int max = 0;
            for (int i = 0; i < s.length(); i++) {
                int val = s.charAt(i) - 'A';
    //when character occurs with even frequency, maximum palindrome length plus by two
                if ((checker & (1L << val)) != 0) max += 2;
    //mark checker with xor to eliminate even frequency and to flag odd frequency with 1
                checker ^= (1L << val); 
            }
    //there is at least one extra character to increase the palindrome length by 1
            if (checker > 0) max++;
            return max;
        }
    }
    

Log in to reply
 

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