使用递归方法判断回文

首先,得了解啥是回文,这个我了解了,不了解的自己去百度(o(´^`)o)。

首先  分析问题,判断回文就是需要从判断第一个与最后一个是否一样,第二个和倒数第二个是否一样,第三个和倒数第三个........依次类推,可能的需要注意的情况有三种:奇数、偶数、就一个字符。

首先,先从简单的不使用递归的方式来写:

//判断是否是回文
import java.util.Scanner;
public class Testpalindrome
{

 public static void main(String args[])
 {
   System.out.println("请输入一段字符串:");
   Scanner scanner=new Scanner(System.in);
   String str=scanner.nextLine();
   int a=str.length();//判断字符串的长度
  
   if(a%2==0)
   {
    for(int i=0;i<a;i++)
    {
   
     if(str.charAt(i)!=str.charAt(a-1-i))
     {
      System.out.println("所输入的字符串不是回文");
      break;
     }
    if(i==a/2)
    {
     System.out.println("所输入的字符串是回文");
     break;
    }
    
    
    }
   
   }
  
   if(a%2==1)
   {
    for(int i=0;i<a;i++)
    {
    
     if(str.charAt(i)!=str.charAt(a-1-i))
     {
      System.out.println("所输入的字符串不是回文");
      break;
     
     }
   if(i==(a+1)/2)
   {
    System.out.println("所输入的字符串是回文");
    break;
   }
   }
    }
   }
}
 

 这个是很容易就能写出的,然后就是使用递归方法的:

//判断是否是回文   使用递归的方法
import java.util.Scanner;
public class Testpalindrome1
{
 public static void main(String args[])
 {
   System.out.println("请输入一段字符:");
   Scanner scanner=new Scanner(System.in);
   String str=scanner.nextLine();
   if(palindromeN(str,0,str.length()-1))
   {
    System.out.println("字符串是回文");
   }
   else
   {
    System.out.println("字符串不是回文");
   }
  
 
 }
 
 
 public static boolean palindromeN(String str,int a,int b)  //a 和 b 相当于两个指针;
 {
  if(a>=b)
  {
   return true;
  }
  if(str.charAt(a)==str.charAt(b))
  {
   return palindromeN(str,++a,--b);
  }
  else
  {
   return false;  
  }
 
 }

 
 就是比较头和尾  然后各自减一 再调用原函数进行判断,很明显,使用递归比不使用递归节省了很多代码长度

猜你喜欢

转载自www.cnblogs.com/wind-and-sky/p/11586372.html
今日推荐