leetcode之路--leetcode 214. 最短回文串(2)
2019-03-01 16:19
337 查看
前言
接上文,继续刷题
leetcode 214. 最短回文串
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
输入: [code]"aacecaaa"输出:"aaacecaaa"
这里的问题和上一篇博客类似。上一篇博客讲的是从一个字符串中找到最长的回文串。该题目是根据已有的字符串,添加最少的字符使其变成回文串。如果首先做了上一篇博客的题目(求取字符串中最长的回文串),那么这个题目就显得比较容易了。
思路:观察给定的几个例子,发现输出的字符串并不是直接将给定的字符串反转添加在字符串头。因为给定的字符串本身就存在回文串的话,添加的字符就会不同,但是只有在从给定字符串的第一个字符算法,求取最长的回文串,将剩下的子串反转添加在字符串头即可。
[code]def t3(s): if len(s)<2: return s length = len(s) maxlen = 1 end = 0 while maxlen<length+1: if s[0:maxlen]==s[0:maxlen][::-1]: end = maxlen maxlen = maxlen +1 return s[end:][::-1]+s
另外,还需要注意特殊情况:
当给定的字符串长度为1时,不需要添加任何字符,它本身就是回文串。
相关文章推荐
- LeetCode 214. 最短回文串
- [LeetCode] Shortest Palindrome 最短回文串
- 【Leetcode】214. Shortest Palindrome 最短回文串
- [LeetCode] Shortest Palindrome 最短回文串
- [LeetCode] 214. Shortest Palindrome 最短回文串
- LeetCode214.最短回文串
- Leetcode Shortest Palindrome (最短回文串)
- LeetCode学习(5)Shortest Palindrome(最短回文串)
- LeetCode--581. Shortest Unsorted Continuous Subarray(最短的无序数组长度)Python
- 【Leetcode】862. Shortest Subarray with Sum at Least K 862. 和至少为 K 的最短子数组
- 利用python 完成 leetcode132 分割回文串 II
- [LeetCode] 409. 最长回文串
- leetcode: Pascal's Triangle | Java最短代码实现
- [LeetCode] Shortest Word Distance III 最短单词距离之三
- 给一个字符串,在后边最短添加什么,才能使得整体变成回文串
- 【LeetCode】214. Shortest Palindrome
- LeetCode-243:Shortest Word Distance (单词最短距离)
- [LeetCode] Find the Closest Palindrome 寻找最近的回文串
- leetcode:Palindrome Partitioning (字符串分割成回文串的所有方式) 【面试算法题】
- leetcode:Palindrome Number (判断数字是否回文串) 【面试算法题】