Simple C++ solution


  • 0
    Z
    class Solution {
    public:
        int longestPalindrome(string s) {
            int arr[52]={0};
            for(int i=0; i<s.size(); i++)
            {
                if(s[i]>='A'&&s[i]<='Z')
                    arr[s[i]-'A'+26]++;
                else
                    arr[s[i]-'a']++;
            }
            int ret=0;
            int hasOdd=0;
            for(int i=0; i<52; i++)
            {
                if(arr[i]%2==0)
                    ret+=arr[i];
                else
                {
                    ret+=arr[i]-1;
                    hasOdd=1;
                }
            }
            return ret+hasOdd;
        }
    };
    

  • 1

    Hi, bro!
    I write a C solution just like your way, but is takes 0ms.
    what happened

    int longestPalindrome(char* s) {
        int counts[52];
        int a = 0;
        bool b = false;
        memset(counts, 0, 52*sizeof(int));
        int i=0;
        int ch;
        int index;
        while( (ch = s[i]) != 0 ){
            index = (ch<'a')?(ch-'A'):(ch-'a'+26);
            counts[index] += 1;
            i++;
        }
        for(int i=0; i<52; i++){
            if(counts[i]%2==0) a+=counts[i];
            else{ a+=counts[i]-1; b = true; }
        }
        return a+b;
    }
    

Log in to reply
 

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