https://leetcode.com/problems/longest-palindrome/description/
Solution 1.
int longestPalindrome(string s) {
int cnt['z'+1] = {0};
int res = 0;
for(int i=0; i<s.size(); i++) {
cnt[s[i]]++;
}
for(int i=0; i<='z'; i++){
res += (cnt[i]& ~1);
}
return res + (res < s.size()); // there is odd when (res < s.size())
}
Solution 2. slower
int longestPalindrome(string s) {
int cnt['z'+1] = {0};
int res = 0;
int odd = 0;
for(int i=0; i<s.size(); i++) {
cnt[s[i]]++;
}
for(int i=0; i<='z'; i++){
if(cnt[i]%2==0)
res += cnt[i];
else {
res += cnt[i] - 1;
odd = 1;
}
}
return res + odd;
}
No comments:
Post a Comment