1.4 Palindrome Permutation

The basic idea of this problem is counting each character’s appearance time.
For even length string: each char should appear even times.
For odd length string: only one char can appear odd time.

I use bool oddCharAppeared to indicate if there was a char appear odd time.

    void countFrequency(string& s , int* frequency){
        int idx = -1;
        for (const char & c : s)
        {
            idx = tolower(c) -'a';
            if ( idx != -1 ) ++frequency[idx];
        }
    }

    bool palindromePermutation(string& s){
        int fre[ 26 ] = { 0 };
        countFrequency(s,fre);
        bool oddCharAppeared = false;
        for (int i = 0; i<26; ++i) {
            if(fre[i]%2 && !oddCharAppeared) oddCharAppeared = true;
            else if (fre[i]%2 && oddCharAppeared) return false;
        }
        return true;
    }

你可能感兴趣的:(String)