409. Longest Palindrome

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

 题目含义:给定一个字符串包含大小写,用字符串中的字符组成一个回文串求符合要求的回文串的最大长度

 

复制代码
 1     public int longestPalindrome(String s) {
 2         if (s.isEmpty()) return 0;
 3         Map<Character, Integer> map = new HashMap<>();
 4         for (int i = 0; i < s.length(); i++) {
 5             Character letter = s.charAt(i);
 6             map.put(letter, map.getOrDefault(letter, 0) + 1);
 7         }
 8         int sum = 0;
 9         int haveOgg = 0;
10         for (Map.Entry<Character, Integer> entry : map.entrySet()) {
11             int count = entry.getValue();
12             if (count % 2 == 0) sum += count;
13             else {
14                 haveOgg = 1;
15                 sum += count - 1;
16             }
17         }
18         return sum + haveOgg;        
19     }
复制代码

 

 

 

 
posted @   daniel456  阅读(110)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示