9ms beats 92.97% No HashSet Java solution


  • 0
    L
    public class Solution {
        public int longestPalindrome(String s) {
            int len = 0;
            // an integer array to save the frequency of the letters in s
            int[] hash = new int[128];
            
            // count the frequency
            for (char c : s.toCharArray())
                hash[c]++;
            
            // scan the frequency array, add all even numbers and odd numbers minus 1 to len
            for (int feq : hash) {
                if (feq == 0) continue;
                if (feq % 2 == 0)   
                    len += feq;
                else 
                	len += feq-1;
            }
            
            // if not all feqs are even, put last odd frequency letter in the middle so we need to add 1 to len
            // if all feqs are even that is len = s.length() just return len
            return (len == s.length()) ? len : len + 1;
        }
    }
    

Log in to reply
 

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