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.
本来写了很多for,师兄的一句话,豁然开朗;也就是代码中关于flag的设置;
int longestPalindrome(char* s) { int len = strlen(s); unsigned int count = 0; int locs[256]; int i, j, k, n = 0; int num[52]; int tmp = 0; int flag = 0; memset(locs, 0, sizeof(locs)); for (i = 0; (s[i] >= 'a'&&s[i] <= 'z') || (s[i] >= 'A'&&s[i] <= 'Z'); i++) { locs[s[i]]++; } for (j = 0; j<256; j++) { if (locs[j] > 0) { num[n++] = locs[j]; tmp++; } } for (k = 0; k < tmp; k++) { if (num[k] % 2 == 0) count = count + num[k]; if (num[k] % 2 == 1) { flag = 1; count = count + num[k] - 1; } } count = (flag == 1) ? (count + 1): count; return count; }