[LeetCode] 131. Palindrome Partitioning 回文分割
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
解法1:dfs, 回溯Backchecking,
解法2:DP
Java:
public class Solution {
List<List<String>> resultLst;
ArrayList<String> currLst;
public List<List<String>> partition(String s) {
resultLst = new ArrayList<List<String>>();
currLst = new ArrayList<String>();
backTrack(s,0);
return resultLst;
}
public void backTrack(String s, int l){
if(currLst.size()>0 //the initial str could be palindrome
&& l>=s.length()){
List<String> r = (ArrayList<String>) currLst.clone();
resultLst.add(r);
}
for(int i=l;i<s.length();i++){
if(isPalindrome(s,l,i)){
if(l==i)
currLst.add(Character.toString(s.charAt(i)));
else
currLst.add(s.substring(l,i+1));
backTrack(s,i+1);
currLst.remove(currLst.size()-1);
}
}
}
public boolean isPalindrome(String str, int l, int r){
if(l==r) return true;
while(l<r){
if(str.charAt(l)!=str.charAt(r)) return false;
l++;r--;
}
return true;
}
}
Java: DP
public class Solution {
public static List<List<String>> partition(String s) {
int len = s.length();
List<List<String>>[] result = new List[len + 1];
result[0] = new ArrayList<List<String>>();
result[0].add(new ArrayList<String>());
boolean[][] pair = new boolean[len][len];
for (int i = 0; i < s.length(); i++) {
result[i + 1] = new ArrayList<List<String>>();
for (int left = 0; left <= i; left++) {
if (s.charAt(left) == s.charAt(i) && (i-left <= 1 || pair[left + 1][i - 1])) {
pair[left][i] = true;
String str = s.substring(left, i + 1);
for (List<String> r : result[left]) {
List<String> ri = new ArrayList<String>(r);
ri.add(str);
result[i + 1].add(ri);
}
}
}
}
return result[len];
}
}
Python:
# Time: O(2^n)
# Space: O(n)
# recursive solution
class Solution:
# @param s, a string
# @return a list of lists of string
def partition(self, s):
result = []
self.partitionRecu(result, [], s, 0)
return result def partitionRecu(self, result, cur, s, i):
if i == len(s):
result.append(list(cur))
else:
for j in xrange(i, len(s)):
if self.isPalindrome(s[i: j + 1]):
cur.append(s[i: j + 1])
self.partitionRecu(result, cur, s, j + 1)
cur.pop() def isPalindrome(self, s):
for i in xrange(len(s) / 2):
if s[i] != s[-(i + 1)]:
return False
return True
Python:
# Time: O(n^2 ~ 2^n)
# Space: O(n^2)
# dynamic programming solution
class Solution:
# @param s, a string
# @return a list of lists of string
def partition(self, s):
n = len(s) is_palindrome = [[0 for j in xrange(n)] for i in xrange(n)]
for i in reversed(xrange(0, n)):
for j in xrange(i, n):
is_palindrome[i][j] = s[i] == s[j] and ((j - i < 2 ) or is_palindrome[i + 1][j - 1]) sub_partition = [[] for i in xrange(n)]
for i in reversed(xrange(n)):
for j in xrange(i, n):
if is_palindrome[i][j]:
if j + 1 < n:
for p in sub_partition[j + 1]:
sub_partition[i].append([s[i:j + 1]] + p)
else:
sub_partition[i].append([s[i:j + 1]]) return sub_partition[0]
Python: wo
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = []
self.helper(res, s, [], 0) return res def helper(self, res, s, cur, l):
if l == len(s):
res.append(list(cur))
return for r in range(l, len(s)):
if self.isPalindrome(s, l, r):
if l == r:
cur.append(s[l])
else:
cur.append(s[l:r+1])
self.helper(res, s, cur, r + 1)
cur.pop() def isPalindrome(self, s, l, r):
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
Python:
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = []
self.dfs(s, [], res)
return res def dfs(self, s, path, res):
if not s:
res.append(path)
return
for i in range(1, len(s)+1):
if self.isPal(s[:i]):
self.dfs(s[i:], path+[s[:i]], res) def isPal(self, s):
return s == s[::-1]
res = []
self.helper(res, s, [], 0) return res
Python:
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
return [[s[:i]] + rest
for i in xrange(1, len(s)+1)
if s[:i] == s[i-1::-1]
for rest in self.partition(s[i:])] or [[]]
C++:
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> out;
partitionDFS(s, 0, out, res);
return res;
}
void partitionDFS(string s, int start, vector<string> &out, vector<vector<string>> &res) {
if (start == s.size()) {
res.push_back(out);
return;
}
for (int i = start; i < s.size(); ++i) {
if (isPalindrome(s, start, i)) {
out.push_back(s.substr(start, i - start + 1));
partitionDFS(s, i + 1, out, res);
out.pop_back();
}
}
}
bool isPalindrome(string s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) return false;
++start;
--end;
}
return true;
}
};
类似题目:
[LeetCode] 132. Palindrome Partitioning II 回文分割 II
All LeetCode Questions List 题目汇总
[LeetCode] 131. Palindrome Partitioning 回文分割的更多相关文章
- 131. Palindrome Partitioning(回文子串划分 深度优先)
Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...
- leetcode 131. Palindrome Partitioning 、132. Palindrome Partitioning II
131. Palindrome Partitioning substr使用的是坐标值,不使用.begin()..end()这种迭代器 使用dfs,类似于subsets的题,每次判断要不要加入这个数 s ...
- [LeetCode] Valid Palindrome 验证回文字符串
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...
- LeetCode Valid Palindrome 有效回文(字符串)
class Solution { public: bool isPalindrome(string s) { if(s=="") return true; ) return tru ...
- [leetcode]131. Palindrome Partitioning字符串分割成回文子串
Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...
- [LeetCode] Shortest Palindrome 最短回文串
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ...
- leetcode 9 Palindrome Number 回文数
Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. S ...
- [LeetCode] Prime Palindrome 质数回文数
Find the smallest prime palindrome greater than or equal to N. Recall that a number is prime if it's ...
- [LeetCode] 266. Palindrome Permutation 回文全排列
Given a string, determine if a permutation of the string could form a palindrome. Example 1: Input: ...
随机推荐
- X2E车载数据记录仪
随着智能驾驶及网联技术深入应用,汽车中传输的数据量与日俱增,包括多种总线数据.视频数据.雷达数据.定位数据等等.据悉,高级别智能驾驶汽车中每秒传输的总线数据就达到G比特级别.而从产品开 ...
- windows10访问ftp中文乱码怎么办?
windows10访问ftp中文乱码怎么办? 打开控制面板 选择时间和区域 选择更改数字格式 点击管理并点击更改系统区域设置 打勾
- hexo利用SAE提高网页打开速度
起因 之前一直觉得网页加载速度其实也还行,就是有两个图标加载的非常慢,经常是网页都出来了,那两个图标还是个方框,要等好久才出来.终于,好好研究了一番,发现那个图标是fontawesome里的,然后字体 ...
- c++中关联容器map的使用
C++关联容器<map>简单总结(转) 补充: 使用count,返回的是被查找元素的个数.如果有,返回1:否则,返回0.注意,map中不存在相同元素,所以返回值只能是1或0. 使用find ...
- python面试题&练习题之嵌套循环
1.打印如下结果: 1*5=5 2*10=20 3*15=45 ... 10*50=500 for i in range(1,11): print(str(i)+'x'+str((i*5))+'='+ ...
- Jmeter 正则表达式提取器详解(Regular Expression Exactor)
Jmeter 正则表达式提取器详解(Regular Expression Exactor) Name(名称):随意设置,最好有业务意义. Comments(注释):随意设置,可以为空 Apply to ...
- P2340 奶牛会展 DP 背包
P2340 奶牛会展 DP \(n\)头牛,每头牛有智商\(s[i]\)情商\(f[i]\),问如何从中选择几头牛使得智商情商之和最大 且 情商之和.智商之和非负 \(n\le 400,-10^3\l ...
- VS2017 Asp.Net调式闪退处理
- CNN中各类卷积总结:残差、shuffle、空洞卷积、变形卷积核、可分离卷积等
CNN从2012年的AlexNet发展至今,科学家们发明出各种各样的CNN模型,一个比一个深,一个比一个准确,一个比一个轻量.我下面会对近几年一些具有变革性的工作进行简单盘点,从这些充满革新性的工作中 ...
- process.env.NODE_ENV理解
1.理解NODE_ENV 在node中,有全局变量process表示的是当前的node进程.process.env包含着关于系统环境的信息.但是process.env中并不存在NODE_ENV这个东西 ...