LEETCODE--Longest Palindrome

    xiaoxiao2021-03-26  21

    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.

    class Solution { public: int longestPalindrome(string s) { int letters[52] = {0}; for(int i = 0; i < s.length(); i++){ if((s[i] - 'Z') > 0){ letters[26 + (s[i] - 'a')]++; }else{ letters[s[i] - 'A']++; } } int odd = 0; int sum = 0; for(int j = 0; j < 52; j++){ if(letters[j] % 2 != 0){ odd = 1; sum += (letters[j] - 1); }else{ sum += letters[j]; } } if(odd == 1) return sum + 1; else return sum; } };
    转载请注明原文地址: https://ju.6miu.com/read-661402.html

    最新回复(0)