首页 > 学院 > 开发设计 > 正文

LEETCODE--Longest Palindrome

2019-11-11 07:34:29
字体:
来源:转载
供稿:网友

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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表