编写一个示例,以递归方式查找一个给定字符串是否为回文


递归是一种以自相似的方式重复项的过程。在编程语言中,如果一个程序允许你在同一个函数内部调用一个函数,那么它被称为该函数的递归调用。

以下是一个示例,使用递归函数查找给定数字的回文。

示例

public class PalindromeRecursion {
   public static boolean isPalindrome(String str){

      if(str.length() == 0 ||str.length()==1){
         return true;
      }

      if(str.charAt(0) == str.charAt(str.length()-1)){
         return isPalindrome(str.substring(1, str.length()-1));
      }
      return false;
   }
   public static void main(String args[]){
      String myString = "malayalam";
      if (isPalindrome(myString)){
         System.out.println("Given String is a palindrome");
      }else{
         System.out.println("Given String is not a palindrome");
      }
   }
}

输出

Given String is a palindrome

更新时间:2020 年 3 月 13 日

903 次浏览

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.