[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: ...
随机推荐
- 《TensorFlow2深度学习》学习笔记(四)对笔记二中的模型增加正确率展示
全部代码如下:(红色部分为与笔记二不同之处) #1.Import the neccessary libraries needed import numpy as np import tensorflo ...
- Codeforces B. Mouse Hunt(强连通分解缩点)
题目描述: Mouse Hunt time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...
- fastjson将json格式字符串转成list集合
1.gameListStr = "[{"gameId":"1","gameName":"哈哈"},{" ...
- RDD&Dataset&DataFrame
Dataset创建 object DatasetCreation { def main(args: Array[String]): Unit = { val spark = SparkSession ...
- TreeMap 的简单解释
TreeMap的构造函数 可以传入 自定义的比较器.Map.SortedMap. put方法: public V put(K key, V value) { Entry<K,V> ...
- Django API接口FK ManyTo Many 模板
Url from django.contrib import admin from django.urls import path, re_path from django.urls import i ...
- bfs与dfs小结
1,bfs适合状态容易存储的题目,如果状态比较难存储,就难以进行记忆化搜索,必然会难以bfs. (比如听说滑雪这个题你用bfs会死得很难看) 2,但是有些题目会很深(比如网格单源最短路),用dfs会跑 ...
- 2019.12.07 java基础
编译时报错,叫做编译失败 class Demo01 { public static void main(String[] args) { int a; a=12; System.out.println ...
- cube.js 新版本试用preosto
cube.js 新的版本添加了更多的数据库的支持,但是目前cubejs-cli 以及官方文档问题还挺多,使用不清晰,文档有明显的错误 以下演示presto 数据库的使用 环境准备 安装新版本的cube ...
- 使用terraform 进行gitlab 代码仓库批量迁移
gitlab 的代码是在文件目录中,这个对于批量迁移很简单,只需要copy 文件夹(但是对于不同gitlab server 可能需要重新设置目录权限) 几个问题 大批量仓库tf resource问 ...