递归实现回文串

package IsHuiwen;

import java.util.Scanner;

//2018 10 14

//20173591 肖成龙 信1705-3

public class IsHuiwen {

public static void main(String args[]) {

Scanner sc=new Scanner(System.in);

String str=sc.nextLine();

if(isPalindrome(str,0)){ System.out.println("字符串 " + str + "是回文串");

        }else{ System.out.println("字符串 " + str +"不是回文串");

        }

}

public static boolean isPalindrome(String str,int index){         

System.out.println(str.charAt(0) + "  " + str.charAt(str.length() - 1));

        if(str.charAt(0) == str.charAt(str.length() - 1)){

         if(str.length() > 2){

         return isPalindrome(str.substring(index+1,str.length()-1),0);

            }else 

             return true;

        }else return false;

首先需要了解的是递归函数的用法,根据简单阶乘用递归方法实现类推回文的递归方法。

回文是正着读反着读一样,利用递归,charAt方法可以选择字符串的第一个charAt0

                                        和最后一个charAtstr.length-1)进行比较,相等的话用tostring0+1length-2,以此类推  

 

原文地址:https://www.cnblogs.com/xcl666/p/9799939.html