409. Longest Palindrome
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 04, 2024
Last updated : July 01, 2024
Related Topics : Hash Table, String, Greedy
Acceptance Rate : 55.339 %
int longestPalindrome(char* s) {
int* reference = (int*) malloc(sizeof(int) * 52);
for (int i = 0; i < 52; i++) {
reference[i] = 0;
}
int index = 0;
while (s[index]) {
printf("%c", s[index]);
if (s[index] < 91) { // uppercase
reference[s[index] - 'A']++;
} else {
reference[s[index] - 'a' + 26]++;
}
index++;
}
int counter = 0;
bool odd = false;
for (int i = 0; i < 52; i++) {
if (reference[i] % 2 == 1) {
odd = true;
counter -= 1;
}
counter += reference[i];
}
free(reference);
return counter + (odd ? 1 : 0);
}
class Solution:
def longestPalindrome(self, s: str) -> int:
refSet = set()
count = 0
for c in s :
if c in refSet :
refSet.remove(c)
count += 2
else :
refSet.add(c)
return count + (1 if len(refSet) > 0 else 0)
class Solution:
def longestPalindrome(self, s: str) -> int:
cnt = Counter(s)
return sum([(x // 2) * 2 for x in cnt.values()]) + (1 if sum([x % 2 for x in cnt.values()]) > 0 else 0)