leetcode_214. 最短回文串 python3
2020-08-29 12:28
1206 查看
目录
一、题目内容
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
示例 1:
输入: "aacecaaa"
输出: "aaacecaaa"
示例 2:
输入: "abcd"
输出: "dcbabcd"
二、解题思路
1.由于是在前面添加字符,因此需要从后往前寻找合适的字符串逆序然后添加到原字符串前面。
2.可以构造逆序的字符串,然后寻找与原字符串相等的回文部分,然后直接把逆序的字符串被过滤掉的部分添加在原字符串前即可构成回文字符串。
三、代码
[code]class Solution: def shortestPalindrome(self, s: str) -> str: length = len(s) if length == 0: return "" s2 = s[::-1] for i in range(length): if s2[i:] == s[:length - i]: break add_before = s2[:i] new_s = add_before + s return new_s if __name__ == '__main__': test = "aaacecaa" s = Solution() ans = s.shortestPalindrome(test) print(ans)悲恋花丶无心之人 CSDN认证博客专家 TensorFlow 深度学习 神经网络 计算机视觉在读研究生,熟悉Pytorch,MXNet,TensorFlow,Keras等深度学习框架,主要涉及的领域有目标检测,语义分割,超分辨率重建,行人重识别等。
相关文章推荐
- LeetCode 214. 最短回文串
- leetcode之路--leetcode 214. 最短回文串(2)
- Leetcode 214. 最短回文串 C++
- LeetCode:分割回文串(Python版本)
- LeetCode 821.字符的最短距离(python)
- LeetCode学习(5)Shortest Palindrome(最短回文串)
- leetcode131 分割回文串 python
- leetcode-最长回文串(python)
- [LeetCode] Shortest Palindrome 最短回文串
- [LeetCode] Shortest Palindrome 最短回文串
- [LeetCode] 214. Shortest Palindrome 最短回文串
- 【Leetcode】214. Shortest Palindrome 最短回文串
- LeetCode--581. Shortest Unsorted Continuous Subarray(最短的无序数组长度)Python
- [和小菜鸡一起刷题(python)] LeetCode 131. 分割回文串 (Palindrome Partitioning)
- python【力扣LeetCode算法题库】409-最长回文串(数学 计数器)
- 【LeetCode】Python实现-581. 最短无序连续子数组
- 利用python 完成 leetcode131 分割回文串
- [和小菜鸡一起刷题(python)] LeetCode 132. 分割回文串 II (Palindrome Partitioning II)
- LeetCode-Python-409. 最长回文串
- LeetCode214.最短回文串