作者: 负雪明烛
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. MEGA软件——系统发育树构建方法(图文讲解) 转载

    转载:http://www.plob.org/2012/12/02/4927.html 一.序列文本的准备 构树之前先将目标基因序列都分别保存为txt文本文件中(或者把所有序列保存在同一个txt文本中 ...

  2. mysql-彻底删除方法

    一.如果是使用yum安装的mysql,使用如下命令进行卸载(不能确定使用何种方式安装的mysql情况下,按后续步骤一一进行处理即可): yum remove mysql mysql-server my ...

  3. ubuntu终端ls颜色配置

    buntu中没有LS_COLORS,/etc/目录中也没有DIR_COLORS,所以这里使用dircolor命令加以解决 1. 利用dircolors命令,查看我们的系统当前的文件名称显示颜色的值,然 ...

  4. kubernetes部署 docker 容器

    docker 容器相对比较简单,不涉及认证授权,只需要本地启动起来即可,唯一需要注意就是添加flannel网络. # yum remove docker-latest-logrotate docker ...

  5. C 语言中求中间数时候防止溢出方法

    当使用二分法时候,注意 mid = left + (right - left) / 2; 这句代码,可以防止溢出!!,千万不能写成 mid = (left + right) / 2 这样写的话,当数字 ...

  6. 零基础学习java------day7------面向对象

    1. 面向对象 1.1 概述 面向过程:c语言 面向对象:java :python:C++等等 面向对象的概念: (万物皆对象)------think in java   everything  in ...

  7. 【leetcode】208. Implement Trie (Prefix Tree 字典树)

    A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...

  8. 【区间dp】- P1880 [NOI1995] 石子合并

    记录一下第一道ac的区间dp 题目:P1880 [NOI1995] 石子合并 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 代码: #include <iostream> ...

  9. 容器的分类与各种测试(三)——deque

    deque是双端队列,其表象看起来是可以双端扩充,但实际上是通过内存映射管理来营造可以双端扩充的假象,如图所示 比如,用户将最左端的buff用光时,map会自动向左扩充,继续申请并映射一个新的buff ...

  10. Linux启动初始化配置文件

    Linux启动初始化配置文件(1)/etc/profile 登录时,会执行. 全局(公有)配置,不管是哪个用户,登录时都会读取该文件. (2)/ect/bashrc Ubuntu没有此文件,与之对应的 ...