/*
* 131. Palindrome Partitioning
My Submissions QuestionEditorial Solution
Total Accepted: 66490 Total Submissions: 239524 Difficulty: Medium
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"]
]
Hide Company Tags Bloomberg
Hide Tags Backtracking
Hide Similar Problems (H) Palindrome Partitioning II
*/
package dfs;
import java.util.*;
public class ParlindromePartition {
public static void main(String[] args) {
// TODO Auto-generated method stub
ParlindromePartition pt = new ParlindromePartition();
String s = "aab";
List<List<String>> res = pt.partition(s);
// System.out.print(res);
}
public List<List<String>> partition(String s) {
/*
* Time complexity is O(n*(2^n)). The function isPalindrome is O(n)
* https://leetcode.com/discuss/18984/java-backtracking-solution if the
* input is "aab", check if [0,0] "a" is palindrome. then check [0,1]
* "aa", then [0,2] "aab".
*
* While checking [0,0], the rest of string is "ab", use ab as input to
* make a recursive call.
*/
List<List<String>> res = new ArrayList<List<String>>();
List<String> cur = new ArrayList<>();
backtrack(res, cur, 0, s);
System.out.print(res);
return res;
}
public void backtrack(List<List<String>> res, List<String> cur, int pos, String s) {
if (pos == s.length()) {
res.add(new ArrayList<String>(cur));
}
for (int i = pos; i < s.length(); i++) {
if (isPalindrome(s, pos, i)) {
cur.add(s.substring(pos, i + 1));
backtrack(res, new ArrayList<String>(cur), i + 1, s);
cur.remove(cur.size() - 1);
}
}
}
public boolean isPalindrome(String str, int l, int r) {
while (l < r) {
if (str.charAt(l++) != str.charAt(r--)) {
return false;
}
}
return true;
}
}
131. Palindrome Partitioning
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given a string s, partition s such that every substring o...
- LeetCode 131 Palindrome Partitioning Given a string s, pa...
- 当一个dfs在for循环里,那么for循环的初始值写成i = start的时候,通常是想让递归在进入下一层的时候不...
- Given a string s, partition s such that every substring o...
- Given a string s, partition s such that every substring o...