leetcode解题笔记-Palindrome Partitioning
来源:互联网 发布:数据库设计原则是什么 编辑:程序博客网 时间:2024/06/06 11:21
练习算法,反思总结
Palindrome Partitioning
题目地址:https://oj.leetcode.com/problems/palindrome-partitioning/
题目大致意思是将一个字符串分成若干子串,要求每个子串都是回文字符串
刚看到题目,想到肯定要利用递归,我刚开始想到的是使用动态规划,我的思路(超时了,但是还是总结一下)是这样的:
利用一个数组arr[i][j]表示从字符串中的第i个字符到第j个字符中的分割方法,比如对于“aab”这个字符串arr[0][1]=[['a','a'],['aa']]。这样从长度1开始,一直处理到字符串的长度,但是这种方案超时了,对于一个n长度的字符串,大致需要(1+...+n)次的计算。该方案代码如下:
<pre name="code" class="html">class Solution: # @param s, a string # @return a list of lists of string def partition(self, s): length = len(s) if length == 0: return [] arr = [[[] for i in range(0,length)] for j in range(0,length)] count = 0 for i in range(1,len(s)+1): for j in range(0,len(s)-i+1): count+=1 if i==1: arr[j][j].append([s[j:j+1]]) else: if s[j:j+i] == s[j:j+i][::-1]: arr[j][j+i-1].append([s[j:j+i]]) for l in range(1,i): left = s[j:j+l] right = arr[j+l][j+i-1] if left!=left[::-1] or len(right)==0: continue for n in range(0,len(right)): arr[j][j+i-1].append([left]+right[n]) print count return arr[0][len(s)-1]
在上述代码的实现过程中遇到个小问题。本来我是这样处理arr[i][j]的,l->1-(j-1),然后将arr[i][l]和arr[l+1][j]合并,这会造成重复。所以修改成s[i:i+l]和arr[l+1][j]合并。
正如我前面说的,计算次数太多了。
现在leetcode推出了提示功能,提示为traceback,回溯法。想想确实能减少次数,因为在处理过程中会剪枝。代码如下:
class Solution: # @param s, a string # @return a list of lists of string def partition(self, s): self.result = [] self.backtrace(s,[]) return self.result def backtrace(self,s,arr): if len(s)==0: self.result.append(arr[::]) for i in range(0,len(s)): strs = s[0:i+1:] if strs == strs[::-1]: arr.append(strs) self.backtrace(s[i+1::],arr) arr.pop()回溯法。回溯时会用一个列表来保存程序经过的路径。当这个路径需要回溯时,就把列表中的最后一项给删掉。
0 0
- leetcode解题笔记-Palindrome Partitioning
- [LeetCode]Palindrome Partitioning,解题报告
- 【LeetCode】Palindrome Partitioning 解题报告
- 【LeetCode笔记】Palindrome Partitioning
- 【LeetCode】Palindrome Partitioning II 解题报告
- [leetcode] 131. Palindrome Partitioning 解题报告
- [leetcode] 132. Palindrome Partitioning II 解题报告
- [Leetcode] 131. Palindrome Partitioning 解题报告
- [Leetcode] 132. Palindrome Partitioning II 解题报告
- Palindrome Partitioning解题报告
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- 【leetcode】Palindrome Partitioning && Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning && Palindrome Partitioning II
- LeetCode Palindrome Partitioning I&&Palindrome Partitioning II
- LeetCode Palindrome Partitioning, Palindrome Partitioning II
- [Leetcode][python]Palindrome Partitioning/Palindrome Partitioning II
- python正则表达式惯用法
- 偷窥iPhone Push Notification的幕后
- POJ 1160 Post Office
- hadoop小文件存储优化
- Linked List Cycle
- leetcode解题笔记-Palindrome Partitioning
- iOS - 非ARC中EXC_BAD_ACCESS异常分析
- 管理中的笑话,笑话中的管理(犹太人的智慧)
- CFBundleVersion in the Info.plist file must contain a higher version than that of the previously upl
- MyEclipse快捷键
- 1029 旧键盘
- linux命令参考:Parallel教程
- cmake并没有想象中好用
- 非常详细的Unity 导出Android教程