LeetCode-409. Longest Palindrome [C++][Java]

该博客介绍了如何利用C++和Java的哈希表来解决LeetCode上的409题——最长回文串。通过计算每个字符出现的次数,确定可以构建的最长回文串长度。文章详细解释了代码逻辑,并提供了两种语言的实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode-409. Longest PalindromeLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/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.

【C++】

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_map<char, int> dict;
        for (auto x : s) {dict[x] += 1;}
        int length = 0, one_count = 0 ;
        for (auto it = dict.begin(); it != dict.end(); it++) {
            if (it->second % 2 == 0) {length += it->second;}
            else {
                if (it->second != 1) {length = length +(it->second-1);}
                ++one_count;
            }
        }
        if (one_count > 0) {return length + 1;}
        return length;
    }
};

【Java】

class Solution {
    public int longestPalindrome(String s) {
        Map<Character, Integer> dict = new HashMap<>();
        for (char ch : s.toCharArray()) {dict.put(ch, dict.getOrDefault(ch, 0) + 1);}
        int length = 0, oneCount = 0;
        for (Character ch : dict.keySet()) {
            int cnt = dict.get(ch);
            if (cnt % 2 == 0) {length += cnt;}
            else {
                if (cnt > 1) {length += cnt - 1;}
                oneCount++;
            }
        }
        if (oneCount > 0) {return length + 1;}
        return length;
    }
}

参考文献

【1】C++中的unordered_map用法详解_zou_albert的博客-CSDN博客

【2】java中遍历字符串的三种方式(String类的方法)_KD____的博客

【3】Java中遍历Map集合的5种方式总结_菜鸟是大神的博客-CSDN博客

【4】哈希表Hash与JAVA集合类Map及其方法put()、getOrDefault()、keySet()、get() 

【5】java.util.Map中的putIfAbsent、computeIfAbsent、computeIfPresent、compute的区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值