http://leetcode.com/onlinejudge#question_131
Question:
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"]
]
Solution:
This is also a DP. I like DP
import java.util.ArrayList;
public class Partition {
public ArrayList<ArrayList<String>> partition(String s) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
int length = s.length();
if(length ==1){
ArrayList<String> a = new ArrayList<String>();
a.add(s);
result.add(a);
return result;
}
for(int i=0; i< length; i++){
String str = s.substring(0, i+1);
if(isP(str)){
if(i+1 == length){
ArrayList<String> a = new ArrayList<String>();
a.add(str);
result.add(a);
}else {
ArrayList<ArrayList<String>> temp = partition(s.substring(i+1));
for(ArrayList<String> a : temp){
a.add(0, str);
result.add(a);
}
}
}
}
return result;
}
public boolean isP(String s){
int length = s.length();
if(length == 1 || length ==0) return true;
int i=0; int j= length-1;
while(s.charAt(i) == s.charAt(j) && i<j){
i++;j--;
}
if(i<j) return false;
else return true;
}
public static void printResult (ArrayList<ArrayList<String>> array){
for(ArrayList<String> a: array){
for(String s: a){
System.out.print("\t" + s);
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "ddfdsfadf";
Partition p = new Partition();
Partition.printResult(p.partition(str));
}
}
分享到:
相关推荐
《LeetCode9:判断回文数——Java实现详解》 在编程的世界里,LeetCode是一个广受欢迎的在线平台,它提供了各种算法问题供程序员们挑战和提升技能。今天我们要探讨的是LeetCode第9题——“回文数”。这道题目要求...
java java_leetcode题解之Partition Labels.java
java java_leetcode题解之Partition Equal Subset Sum.java
java java_leetcode题解之Partition to K Equal Sum Subsets.java
java java_leetcode题解之Palindrome Permutation.java
c c语言_leetcode 0009_palindrome_number.zip
java java_leetcode题解之Palindrome Permutation II.java
python python_leetcode题解之131_Palindrome_Partitioning
java入门 java_leetcode题解之009_Palindrome_Number
java java_leetcode题解之Longest Chunked Palindrome Decomposition.java
js js_leetcode题解之9-palindrome-number.js
java java_leetcode题解之Can Make Palindrome from Substring.java
python python_leetcode题解之132_Palindrome_Partitioning_II
python python_leetcode题解之086_Partition_List
javascript js_leetcode题解之131-palindrome-partitioning.js
c语言入门 C语言_leetcode题解之09-palindrome-number.c
python python_leetcode题解之234_Palindrome_Linked_List.py
c++ C++_leetcode题解之763. Partition Labels.cpp
javascript js_leetcode题解之132-palindrome-partitioning-ii.js
javascript js_leetcode题解之86-partition-list.js