20170321-leetcode-131-Palindrome partitioning
来源:互联网 发布:可以收听香港电台软件 编辑:程序博客网 时间:2024/06/06 06:51
1.Description
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"]]
https://leetcode.com/problems/palindrome-partitioning/#/description
解读
输入:一个字符串,把该字符串分割,使得每个字符串都构成回文,输出所有满足条件的分割结果
求解该问题,可以采取回溯和循环的策略。
如果输入“aab”,循环判断[0:1],[0:2],[0:3] (左开右闭),对于其中的每一个采取深度优先搜索(DFS)
https://leetcode.com/problems/palindrome-partitioning/#/solutions
如上图,对于[0:1]—>分割成[a]+[a][a][b]/[a][ab]
对于[0:2]—>分割成[aa]+[b]
对于[0:3]—>分割成[aab]
2.Solution
class Solution(object): def partition(self, s): return [[s[:i]] + rest for i in range(1, len(s) + 1) if s[:i] == s[i - 1::-1] for rest in self.partition(s[i:])] or [[]]
https://leetcode.com/problems/palindrome-partitioning/#/solutions
if s[:i] == s[i - 1::-1],s[i-1::-1]是s[:i]的逆序,判断是否为回文
上述代码可以修改为:
class Solution(object): def mypartition(self, s): ans = [] for i in range(1, len(s) + 1): if s[:i] == s[i - 1::-1]: for rest in self.partition(s[i:]): ans.append([s[:i]] + rest) print(ans) if not ans: return [[]] return ans
0 0
- 20170321-leetcode-131-Palindrome partitioning
- LeetCode: Palindrome Partitioning [131]
- LeetCode 131 Palindrome Partitioning
- LeetCode(131)Palindrome Partitioning
- [leetcode 131] Palindrome Partitioning
- [leetcode]131 Palindrome Partitioning
- LeetCode 131 Palindrome Partitioning
- leetcode ||131、Palindrome Partitioning
- LeetCode(131) Palindrome Partitioning
- leetcode 131: Palindrome Partitioning
- Leetcode #131 Palindrome Partitioning
- 131 Palindrome Partitioning [Leetcode]
- LeetCode 131 Palindrome Partitioning
- Leetcode 131:Palindrome Partitioning
- 【LeetCode-131】Palindrome Partitioning
- Leetcode 131 Palindrome Partitioning
- [leetCode 131]Palindrome Partitioning
- Leetcode 131 Palindrome Partitioning
- 浅尝Python 的GUI编程
- 微信小程序使用e.target.dataset的问题
- 内网 大数据同步至外网(云服务器) 一
- openssl系列--前言
- 抽奖型电商活动后台技术实践
- 20170321-leetcode-131-Palindrome partitioning
- android CoordinatorLayout使用(综合案例)
- 深入理解HTTP协议(转) 浏览器和服务器如何通信(HTTP协议)
- OFBiz组件下每个目录的作用及其大致功能
- 用gulp前段自动化构建工具的小心了,关于angular.js中取消success,error的功能,用then和.catch
- SVN working copy locked解决方法
- Angularjs利用$location.search()获取url参数问题
- 重置SQLSERVER表的自增列,让自增列重新计数
- 安卓第三方登录之微信登录(图文详解)