409. Longest Palindrome的C++算法

来源:互联网 发布:长城宽带续费网络网址 编辑:程序博客网 时间:2024/06/03 10:47

奇数直接加,偶数去掉一个再加,中间可以出现一个奇数。

class Solution {public:int longestPalindrome(string s) {vector<int> count = { 0 };count.resize(60);for (int i = 0; i < s.length(); i++)count[s[i] - 'A']++;int single = 0;int result=0;for (int i = 0; i < count.size(); i++){if (count[i] % 2 == 0) result = result + count[i];else{single = 1;result = result + count[i] - 1;}}return result + single;}};

或者另一种思路,统计奇数字母的种类:

int longestPalindrome(string s) {    int odds = 0;    for (char c='A'; c<='z'; c++)        odds += count(s.begin(), s.end(), c) & 1;    return s.size() - odds + (odds > 0);}
奇数和1按位与是1,偶数和1按位与是0,因为奇数的最低位一定是1。

原创粉丝点击