Palindrome Partitioning in Java

来源:互联网 发布:mac层的作用 编辑:程序博客网 时间:2024/06/07 09:41

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.

For example, given s = "aab",
Return

[  ["aa","b"],  ["a","a","b"]]


The main idea of the algorithm: 

1) 把原字符串分解成2部分,str1[0, i] 和 str2[i+1, end ]  2个部分。 比如:abba可以根据 遍历一遍 i  分为:i=1: [a, bba] ,  i=2: [ab, ba],  i=3: [abb, a] 

2) 判断第一部分是否是回文,如果是,则递归判断第二部分,重复1)。在第二部分的结果前面加上str1 的结果即可!

Solution Class: 

 import java.util.ArrayList;public class Solution {                                                                                                                                                    public ArrayList<ArrayList<String>> Palin(String s) {         ArrayList<ArrayList<String>> out = new ArrayList<ArrayList<String>>();  int len = s.length();  for(int i = 0; i< len; i++){ String str1 = s.substring(0,i+1); String str2 = s.substring(i+1); if(isPalindrome(str1)){  if( i+1 == len ){   ArrayList<String> a = new ArrayList<String>();                      a.add(str1);                                  out.add(a); } else { ArrayList<ArrayList<String>> temp =Palin(str2); for(ArrayList<String> a : temp){                    a.add(0, str1);                    out.add(a);             } } }}  return out; }                                                                                                                                                 }


add method to check if the string is palindrome: 
 //check if the string is palindrome public boolean isPalindrome(char[] c, int start, int end) {  while(start <= end && c[start] == c[end]) {    start++;    end--;    if(start >= end)        return true; } return false; }


print the results: 
 public void printResult(ArrayList<ArrayList<String>> arr){ for( ArrayList<String> sl : arr){ System.out.print('['); for( String str : sl) {   System.out.print(str + " ");   } System.out.println(']');} }

Main method: 

import java.util.ArrayList;public class Main {public static void main(String[] args){Solution p = new Solution();String s = "abbbba";//test booleanSystem.out.println(p.isPalindrome(s));//testp.printResult(p.Palin(s)); }}





原创粉丝点击