3ms C++ Solution


  • 0
    X
    class Solution {
    public:
        int longestPalindrome(string s) {
            if (s.size() == 0) {
                return 0;
            }
            
            int hash[256] = {0};
            
            for (auto i : s) {
                hash[i]++;
            }
            
            bool isOdd = false;
            bool isOne = false;
            int n = 0;
            for (int i = 0; i < 256; i++) {
                if (hash[i] == 0) {
                    continue;
                }
                
                if (hash[i] == 1) {
                    isOne = true;
                    continue;
                }
                
                if (hash[i] % 2 == 0) {
                    n += hash[i];
                }
                else {
                    int x = hash[i] / 2;
                    n += x * 2;
                    isOdd = true;
                }
            }
            
            if (isOne && (!isOdd) && n == 0) {
                return 1;
            }
            
            if (isOne || isOdd) {
                n++;
            }
            
            return n;
        }
    };
    

Log in to reply
 

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