Longest Palindrome

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note: Assume the length of given string will not exceed 1,010.

Example: Input: "abccccdd"

Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Solution : Count number of odd occurences

int longestPalindrome(string s) {
    int arr[256] = {0};
    for (auto ch: s) {
        arr[ch] += 1;
    }

    int oddCount = 0;
    for (int i=0; i<256; i++) {
        if (arr[i] % 2) {
            oddCount += 1;
        }
    }
    return s.size() - max(0, oddCount-1);
}

Solution: Using Count function

    int longestPalindrome(string s) {
        // write your code here
        int odds = 0;
        for (char c='A'; c <= 'z'; c++) {
            odds += count(s.begin(), s.end(), c) & 1;
        }

        return s.size() - max(0, odds-1);
    }

results matching ""

    No results matching ""