[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: ...
随机推荐
- 微信小程序~项目步骤和流程
从运营的角度讲制作,不是从程序的角度讲开发,所以简单明晰,通俗易懂,小白也能按照流程完成制作. 微信小程序制作步骤及流程 1.确定好微信小程序的的定位和目的 如行业,功能,内容,目标用户,目标市场,意 ...
- js实现文本框自动显示两位小数
转自https://blog.csdn.net/qiji2011/article/details/81270552 1.js: //保留2位小数,如:2,会在2后面补上00.即2.00 functio ...
- Linux 安装Anaconda 提示“bunzip2: command not found”
问题: 安装Anaconda 过程中提示缺少“bunzip2” 解决思路: 由于缺少bunzip2 包,需要通过yum 方式安装bzip2 yum install -y bzip2 Linux bun ...
- Java基础(八 前面补充)
1.笔记 1.局部内部类 如果一个类是定义在一个方法内部的,那么这就是一个局部内部类. “局部”:只有当前所属的方法才能使用它,出了这个方法外面就不能用了. 定义格式: 修饰符 class 外部类名称 ...
- 11 open source business models
https://www.zdnet.com/article/11-open-source-business-models/ Critics are always claiming open sourc ...
- OKR的两个基本原则
<启示录>作者,前易贝高级副总裁,硅谷产品集团创始人马蒂·卡根在<OKR工作法>的序言中提到了目标管理法的两个原则: 不要告诉下属具体怎么做,要告诉他们你要什么,他们就会给你满 ...
- win7虚拟机安装
https://blog.csdn.net/qq_16503045/article/details/81904986 iso下载地址 https://msdn.itellyou.cn/
- sdcf day4 qaq模拟赛总结
目录 链接 总结 链接 点这里,O(∩_∩)O~ 总结 我还是太菜了,第二题提交了\(8\)遍,真心无语了 总结来看 一是思维能力弱,第二个思维题想了很长时间,想不出来 二是代码能力弱,尽管代码短,但 ...
- QML学习(一)——<简要概念知识点>
转载:https://www.cnblogs.com/dengyg0710/p/10644936.html 1.一个 QML 文档有且只有一个根元素. 2.QML 元素名后所有内容使用 {} 包围起来 ...
- span 不使用float 靠右对齐且垂直居中
一般让div 里的span 靠右对齐用的方法比较多的是float:right. 这次由于各种原因我不想用float 先看效果: HTML 部分 <div class="customer ...