Simple idea


  • 0
    B

    The idea is - count each character, and then sum all even numbers and the even part for odd numbers; if any odd number exists, add extra 1;

    public class Solution {
        public int longestPalindrome(String s) {
            int[] m = new int[128];
            for(char ch : s.toCharArray()) m[ch]++;
            
            int sum = 0;
            for (int i = 0; i < 128; i++) {
                sum += m[i]/2*2;
                m[i] = m[i]%2;
            }
            
            int i = 0;
            while (i < 128 && m[i] == 0) i++;
            
            if (i < 128) sum++;
            return sum;
        }
    }
    

Log in to reply
 

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