栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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 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 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的区别

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1034956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号