作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/longest-palindrome/

  • Difficulty: Easy

题目描述

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. 先加上所有能够成偶数次的字符串次数:

    • 如果一个字符出现了偶数次,那么一定可以是最终回文字符串的一部分,加上该字符出现的次数;
    • 如果一个字符出现了奇数v次,那么可以加上v-1次(只使用偶数次这个字符);
  2. 如果有出现过奇数次的字符,那么最后结果+1,代表把该奇数字符放在中间。

Python解法:

class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
count = collections.Counter(s)
res = 0
prime = 0
for k, v in count.items():
if v % 2 == 1:
res += v - 1
prime = 1
else:
res += v
return res + prime

C++代码如下:

class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> count;
for (char c : s)
++count[c];
int res = 0;
bool hasOne = false;
for (auto d : count) {
if (d.second % 2 == 0)
res += d.second;
else {
res += d.second - 1;
hasOne = true;
}
}
if (hasOne)
++res;
return res;
}
};

方法二:HashSet

看了高票的答案,可以HashSet的方法,统计一个字符是否出现了偶数次,一增一减相抵消,这样的个数*2,如果HashSet中还有元素再加上1即可。

Java代码如下:

public class Solution {
public int longestPalindrome(String s) {
HashSet<Character> hashset=new HashSet<Character>();
int count=0;
for(int i =0; i< s.length(); i++){
if(hashset.contains(s.charAt(i))){
hashset.remove(s.charAt(i));
count++;
}else{
hashset.add(s.charAt(i));
}
}
if(!hashset.isEmpty()) return count*2 +1;
return count*2;
}
}

AC: 23 ms

虽然只遍历了一遍,但是用到了HashSet,因此效率没我的高。

方法三:次数除以2再乘以2

用两个int[26],分别保存大小写字符,统计字符出现的对数,最后判断这些字符对数相加是否等于原字符的长度,如果不等说明有奇数的出现,在/2的时候被舍去了。方法思想挺巧妙的。

Java代码如下:

public int longestPalindrome(String s) {
int[] lowercase = new int[26];
int[] uppercase = new int[26];
int res = 0;
for (int i = 0; i < s.length(); i++){
char temp = s.charAt(i);
if (temp >= 97) lowercase[temp-'a']++;
else uppercase[temp-'A']++;
}
for (int i = 0; i < 26; i++){
res+=(lowercase[i]/2)*2;
res+=(uppercase[i]/2)*2;
}
return res == s.length() ? res : res+1; }

日期

2017 年 1 月 8 日
2018 年 11 月 16 日 —— 又到周五了!
2019 年 2 月 18 日 —— 继续学习~
2020 年 3 月 19 日 —— 恰巧每年都做一遍这个题

【LeetCode】409. Longest Palindrome 解题报告(Python & C++)的更多相关文章

  1. 24. leetcode 409. Longest Palindrome

    409. Longest Palindrome Given a string which consists of lowercase or uppercase letters, find the le ...

  2. [LeetCode] 409. Longest Palindrome 最长回文

    Given a string which consists of lowercase or uppercase letters, find the length of the longest pali ...

  3. LeetCode 409. Longest Palindrome (最长回文)

    Given a string which consists of lowercase or uppercase letters, find the length of the longest pali ...

  4. LeetCode 409 Longest Palindrome

    Problem: Given a string which consists of lowercase or uppercase letters, find the length of the lon ...

  5. LeetCode——409. Longest Palindrome

    题目: Given a string which consists of lowercase or uppercase letters, find the length of the longest ...

  6. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  7. 【leetcode】409. Longest Palindrome

    problem 409. Longest Palindrome solution1: class Solution { public: int longestPalindrome(string s) ...

  8. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  9. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

随机推荐

  1. 【samtools】运行报错: error while loading shared libraries:libcrypto.so.1.0.0或libncurses.so.5或libtinfow.so.5

    samtools用conda安装后,总是出现共享库缺失的报错.即便你刚安装samtools时可以用,但后面在同一环境中安装其他相关软件,有可能产生了冲突,导致库替换,因而报错. 避免这种情况,可能最好 ...

  2. R语言与医学统计图形-【14】ggplot2几何对象之直方密度图

    ggplot2绘图系统--几何对象之直方图.密度图 1.直方图 参数. geom_histogram(mapping = , data = , stat = 'bin', #统计变换,概率密度为den ...

  3. 蛋白组DIA分析:Spectronaut软件使用指南

    官方文档: https://biognosys.com/media.ashx/spectronautmanual.pdf 0. 准备 Spectronaut软件是蛋白组DIA分析最常用的谱图解析软件之 ...

  4. 57-Palindrome Linked List

    Palindrome Linked List My Submissions QuestionEditorial Solution Total Accepted: 46990 Total Submiss ...

  5. CSS上下左右居中对齐

    上下左右居中对齐 display:  inline/inline-block 将父元素(容器)设定 text-align: center: 即可左右置中. display: block 将元素本身的 ...

  6. android studio 编译 Android dependency has different version

    找了一圈,终于在大佬的博客中找到了解决方法. 附链接:https://blog.csdn.net/u010725171/article/details/81232183 Android depende ...

  7. day02 Rsyuc备份服务器

    day02 Rsyuc备份服务器 一.备份 1.什么是备份 备份就是把重要的数据或者文件复制一份保存到另一个地方,实现不同主机之间的数据同步 一般数据比较重要的情况下,数据如果丢失很容易找不回来了的, ...

  8. Linux系统中安装软件方法总结

    Linux系统中安装软件方法总结 [1]Linux系统中安装软件的几种方式 [2] Linux配置yum源(本地源和网络源) [3] SuSE下zypper源配置 [4] SUSE zypper 本地 ...

  9. 【Java多线程】Java 原子操作类API(以AtomicInteger为例)

    1.java.util.concurrent.atomic 的包里有AtomicBoolean, AtomicInteger,AtomicLong,AtomicLongArray, AtomicRef ...

  10. get请求url参数中有+、空格、=、%、&、#等特殊符号的问题解决

    url出现了有+,空格,/,?,%,#,&,=等特殊符号的时候,可能在服务器端无法获得正确的参数值,如何是好?解决办法将这些字符转化成服务器可以识别的字符,对应关系如下:URL字符转义 用其它 ...