Leetcode Longest Palindrome problem solution YASH PAL, 31 July 2024 In this Leetcode Longest Palindrome problem solution, You are given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, “Aa” is not considered a palindrome here. Problem solution in Python. class Solution: def longestPalindrome(self, s: str) -> int: a = set() for l in s: if l not in a: a.add(l) else: a.remove(l) return len(s) - len(a) + 1 if len(a) else len(s) Problem solution in Java. public class Solution { public int longestPalindrome(String s) { if(s==null|| s.length()==0) return 0; if(s.length()==1) return 1; int[] alpha=new int[128]; int max_length=0; for(char c:s.toCharArray()){ alpha[c]++; if(alpha[c]==2) { max_length+=2; alpha[c]=0; } } if(s.length()>max_length) return max_length+1; else return max_length; } } Problem solution in C++. int longestPalindrome(string s) { if (s.size() < 2) return s.size(); int ht[256]{0}; for (auto a : s) ++ht[a]; int length{0}; bool has_odd{false}; for (int i = 65; i <= 122; ++i) { if (ht[i]) { length += ht[i]; if (ht[i] % 2 == 1) { if (!has_odd) has_odd = true; length -= 1; } } } if (has_odd) ++length; return length; } Problem solution in C. #include<string.h> int longestPalindrome(char * s){ int count[52]={0}; int len=strlen(s); for(int i=0;i<len;i++){ if(s[i]<='Z' && s[i]>='A'){ count[26+s[i]-'A']++; }else{ count[s[i]-'a']++; } } int ans=0; bool odd=false; for(int i=0;i<52;i++){ if(count[i]%2){ ans+=(count[i]-1); odd=true; }else{ ans+=count[i]; } } return odd?ans+1:ans; } coding problems