递归方式判断一个字符串是否为回文字符串

2017-05-31  本文已影响162人  cactusjunjie

如题,代码如下:

/*

* 递归方式判断一个字符串是否为回文字符串

*/

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;

     }

}

上一篇 下一篇

猜你喜欢

热点阅读