Palindrome Partitioning in Java

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 boolean
		System.out.println(p.isPalindrome(s));
		
		//test
		p.printResult(p.Palin(s));
		 
		
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值