如題,代碼如下:
/*
* 遞歸方式判斷一個(gè)字符串是否為回文字符串
*/
public class PartitionTest{
? ? ? ?public static void main(String[] args) {?
? ? ? ? ? ? ? String str = "123456654321";
? ? ? ? ? ? ? System.out.println("srcString = "+str);
? ? ? ? ? ? ? System.out.println("srcString is "+(isPartition(str)?"":" not ")+" Partition");
? ? ? ?}
? ? ? /*
? ? ? ?* 實(shí)現(xiàn)原理:
? ? ? ?* 1、將原始字符串轉(zhuǎn)換成字符數(shù)組;
? ? ? ?* 2、對(duì)比首尾兩字符是否相等,如果該兩字符不相等則直接返回false,否則對(duì)截取首尾兩字符的子串繼續(xù)調(diào)用該方法;
? ? ? ?* 3、對(duì)原始字符串的子串重復(fù)以上操作,直到子串為空;
? ? ? ?*/
? ? ? ?public static boolean isPartition(String str){
? ? ? ? ? ? ? char[] cArray = str.toCharArray();
? ? ? ? ? ? ? int i = 0;
? ? ? ? ? ? ? int j = cArray.length-1;
? ? ? ? ? ? ? while(i<j){
? ? ? ? ? ? ? ? ? ? ? ?//首尾兩字符不相等,返回false
? ? ? ? ? ? ? ? ? ? ? ?if(cArray[i]!=cArray[j]){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? ? ? ? ?}else{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? System.out.println("substring = "+str.substring(i+1, j));
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return isPartition(str.substring(i+1, j));
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ?}
? ? ? ? ? ?//遍歷所有子串,返回true
? ? ? ? ? return true;
? ? ?}
}