博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
409. Longest Palindrome
阅读量:2351 次
发布时间:2019-05-10

本文共 1911 字,大约阅读时间需要 6 分钟。

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.

我的想法

遍历字符串,对字符频率进行统计,所有的偶数都可以直接count。奇数次字符需要注意(这个bug找了好久!):每个字符不是一个整体,假设a出现了5次,我可以只count 4!。这意味着所有的奇数次字符在count的时候需要-1。而在函数返回时需要注意(这里第一次也写错了!!):如果有>=3的奇数次字符需要在最后返回时+1,以构成奇数型回文串...aba...。如果没有,比如...aa...,不要+1!!!!

class Solution {
public int longestPalindrome(String s) {
if(s == null || s.length() == 0) return 0; Map
map = new HashMap<>(); int res = 0; for(int i = 0; i < s.length(); i++) {
Integer count = map.get(s.charAt(i)); if(count != null) {
map.put(s.charAt(i), ++count); } else {
map.put(s.charAt(i), 1); } } ArrayList
list = new ArrayList<>(map.values()); boolean oddCenter = false; for(int i = 0; i < list.size(); i++){
int count = list.get(i); if(count % 2 == 1) oddCenter = true; res += (count % 2 == 0) ? count : count - 1; } return oddCenter ? res + 1 : res; }}

解答

leetcode solution: Greedy

写法很简洁,因为a-Z本身只有128,可以直接用数组来操作。利用v / 2 * 2先取整再乘二,避免我写的那种冗余判断。但其实没有太明白这个为什么算贪心。

class Solution {
public int longestPalindrome(String s) {
int[] count = new int[128]; for (char c: s.toCharArray()) count[c]++; int ans = 0; for (int v: count) {
ans += v / 2 * 2; //判断是否有unique center if (ans % 2 == 0 && v % 2 == 1) ans++; } return ans; }}

转载地址:http://nkqvb.baihongyu.com/

你可能感兴趣的文章
rman本库恢复性测试
查看>>
IBM TSM磁带管理操作小记一则
查看>>
ORA-00258: NOARCHIVELOG 模式下的人工存档必须标识日志
查看>>
Java调用bat文件
查看>>
此责任无可用函数
查看>>
java获取数字和汉字
查看>>
excel Option Explicit webadi
查看>>
ICX错误
查看>>
windows Xp NTLDR is missing
查看>>
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
查看>>
Centos 6.x 安装配置MySQL
查看>>
-source 1.5 中不支持 diamond 运算 请使用 -source 7 或更高版本以启用
查看>>
jar包读取资源文件报错:找不到资源文件(No such file or directory)
查看>>
超简单:Linux安装rar/unrar工具与解压到目录示例
查看>>
Eclipse创建Maven Java8 Web项目,并直接部署Tomcat
查看>>
RedHad 7.x服务器操作记录
查看>>
BindException: Cannot assign requested address (Bind failed)解决办法
查看>>
Centos7:Docker安装Gitlab
查看>>
Kafka日志配置
查看>>
logstash 6.x 收集syslog日志
查看>>