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.
- 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.
C Solutions 1:
int longestPalindrome(char* s) {
int ht[256] = {0}, res = 0;
char *p;
for (p = s; *p; p++) {
if (ht[*p]) {
res += 2;
ht[*p] = 0;
}
else ht[*p]++;
}
int i;
for (i = 0; i < 256; i++) {
if (ht[i]) {
res++;
break;
}
}
return res;
}
C Solutions 2:
int longestPalindrome(char* s) {
int flag[256] = {0}, odd = 0, res = 0;
for (; *s; s++) {
if (flag[*s]) {
odd--;
flag[*s] = 0;
res += 2;
}
else {
flag[*s] = 1;
odd++;
}
}
return res + !!odd;
}
Summary:
- Nothing to say.
LeetCode: 409. Longest Palindrome





近期评论