[string]409. Longest Palindrome

409. Longest Palindrome

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.

Example 1:

Input: s = “abccccdd”
Output: 7
Explanation: One longest palindrome that can be built is “dccaccd”, whose length is 7.

Example 2:

Input: s = “a”
Output: 1
Explanation: The longest palindrome that can be built is “a”, whose length is 1.

Constraints:

1 <= s.length <= 2000
s consists of lowercase and/or uppercase English letters only.

solution1贪心、奇偶性

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char, int> count;
        int ans = 0;
        for (char c : s)
            ++count[c];
        for (auto p : count) {
            int v = p.second;
            ans += v / 2 * 2;
            if (v % 2 == 1 and ans % 2 == 0)
                ++ans;
        }
        return ans;
    }
};

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/longest-palindrome/solution/zui-chang-hui-wen-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

1.用哈希表统计每个字符出现的次数
2.判断奇偶性:
若字符出现次数为偶数,则肯定能够组成回文串,计入累加器
若为奇数,添加个数-1并计入累加器,并且标记存在中心字符

class Solution {
public:
	int longestPalindrome(string s) {
		unordered_map<char, int> hash;
        for (auto x : s) hash[x] ++;
        int res = 0, center = 0;

        for (auto item : hash){
            if (item.second % 2 == 0) 
                res += item.second;
            else{
                res += item.second - 1;
                center = 1;
            }
        }
        return res + center;
	}
};

作者:wangtao27
链接:https://leetcode.cn/problems/longest-palindrome/solution/li-yong-ha-xi-biao-yu-qi-ou-xing-ben-ti-ke-jie-by-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

vector<int> m(128,0);
int len=0;
for(auto c:s) { 
    if(m[c]&1) len+=2; 
    m[c]++;
}
if(len<s.size()) len++;
return len;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值