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; }
本文介绍了一种用于寻找由给定字符串中的字符构建的最长回文串的方法。该算法考虑了大小写的区别,并通过计数每个字符出现次数来确定最长回文串的长度。通过对字符计数进行奇偶判断,确保了最终结果的有效性。
380

被折叠的 条评论
为什么被折叠?



