LintCode python 小白-简单题-627最长回文串
来源:互联网 发布:java 字符串拼接 效率 编辑:程序博客网 时间:2024/05/29 03:35
题目:给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。
数据是大小写敏感的,也就是说,”Aa” 并不会被认为是一个回文串。
假设字符串的长度不会超过 1010。
样例:给出 s = “abccccdd” 返回 7
一种可以构建出来的最长回文串方案是 “dccaccd”。
思路:
- 输入的是一个字符串
- 将字符串切割成一个一个的元素,然后能够成对的基本就能构建回文串。
- 将字符串先转换为列表,然后列表的每一个元素是字符串的每一个字母,排好序,这样子相同的元素会排在一起。
- 因为是两个成对,所以若有奇数的相同元素,也只取偶数个,另外一个不能满足要求的字母。
- 我们不能忽略中位数,即中间可以是独立的一个,并且是列表中随便的一个,为了求最大回文串,若有使单独的字母,将其放在中间,使回文串的长度+1。
代码:
class Solution: # @param {string} s a string which consists of lowercase or uppercase letters # @return {int} the length of the longest palindromes that can be built def longestPalindrome(self, s): # Write your code here slist=list(s) #将字符串转变为列表 slist.sort() #排序 result=[] #存放满足回文串的字母 i=0 #循环初始化 j=0 #回文串的长度初始为0 while i <len(slist)-1: if slist[i]==slist[i+1]: i+=2 j+=2 else: i+=1 if j<len(slist): #判断是否有独立的字母 return j+1 else: return j
阅读全文
1 0
- LintCode python 小白-简单题-627最长回文串
- lintcode(627)最长回文串
- LintCode 最长回文串
- lintcode:最长回文串
- 最长回文串-LintCode
- LintCode-最长回文子串
- LintCode:最长回文子串
- lintcode,最长回文子串
- [lintcode]最长回文子串
- lintcode -- 最长回文子串
- LintCode之最长回文串
- 最长回文子串-LintCode
- LintCode 最长回文子串
- lintcode最长回文子串
- [LintCode 200] 最长回文字符串(Python)
- LintCode python 小白-简答题-回文数
- LintCode python 小白-简单题-638-Strings Homomorphism
- LintCode python 小白-简单题-569各位相加
- 软件生命周期
- MongoDB快速入门
- 基于SSM或者SSH的三种单元测试方式
- 文章标题
- 51nod 1117 聪明的木匠
- LintCode python 小白-简单题-627最长回文串
- android开源库---Dagger2入门学习(为什么使用)
- 【C语言】C语言实现动态通讯录
- cardview向下兼容API21以下
- hdu 6040 Hints of sd0061(STL)
- Maven和SBT学习日记1
- hdu2035 人见人爱A^B(C语言)
- 数据库的定时任务
- android事件分发机制