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));
}
}
分享到:
相关推荐
LeetCode Palindrome Number解决方案 在本节中,我们将讨论如何确定一个整数是否是一个回文数。一个整数是一个回文数当它从左到右读取和从右到左读取相同。 问题描述: 给定一个整数,判断它是否是一个回文数。 ...
《LeetCode9:判断回文数——Java实现详解》 在编程的世界里,LeetCode是一个广受欢迎的在线平台,它提供了各种算法问题供程序员们挑战和提升技能。今天我们要探讨的是LeetCode第9题——“回文数”。这道题目要求...
c c语言_leetcode 0009_palindrome_number.zip
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
c语言基础 c语言_leetcode题解之0086_partition_list.zip
c c语言_leetcode题解之0416_partition_equal_subset_sum
python python_leetcode题解之125_Valid_Palindrome
# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...