遞歸方式判斷一個字符串是否為回文字符串

如題,代碼如下:

/*

* 遞歸方式判斷一個字符串是否為回文字符串

*/

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");

? ? ? ?}

? ? ? /*

? ? ? ?* 實現原理:

? ? ? ?* 1、將原始字符串轉換成字符數組;

? ? ? ?* 2、對比首尾兩字符是否相等,如果該兩字符不相等則直接返回false,否則對截取首尾兩字符的子串繼續調用該方法;

? ? ? ?* 3、對原始字符串的子串重復以上操作,直到子串為空;

? ? ? ?*/

? ? ? ?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;

? ? ?}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容