Determined using a recursive method palindromic

First of all, we have to understand what is a palindrome, which I understand, do not understand their own to Baidu (o ( '^ `) o).

First analyze the problem, determine palindrome is a need to determine whether the first and the last, like, the second and penultimate whether, as the third and last third ........ and so on, possible need to pay attention in three ways: odd, even, to a character.

First, start with a simple manner without using recursion to write:

// determine whether it is a palindrome
import java.util.Scanner;
public class Testpalindrome
{

 public static void main(String args[])
 {
   System.out.println ( "Enter a string:");
   Scanner Scanner Scanner new new = (the System.in);
   String = scanner.nextLine STR ();
   int str.length A = (); // string Analyzing the length of the
  
   IF (a% 2 == 0)
   {
    for (int I = 0; I <a; I ++)
    {
   
     (! str.charAt (I) str.charAt = (. 1-a-I)) IF
     {
      the System. out.println ( "the input string is not a palindrome");
      BREAK;
     }
    IF (a == I / 2)
    {
     System.out.println ( "input character string is a palindrome");
     BREAK;
    }
    
    
    }
   
   }
  
   IF (A == 2%. 1)
   {
    for (int I = 0; I <A; I ++)
    {
    
     IF (! str.charAt (I) str.charAt = (. 1-A-I))
     {
      System.out.println ( "the input string is not a palindrome");
      BREAK;
     
     }
   IF (I == (. 1 + A) / 2)
   {
    System.out.println ( "input character string is a palindrome ");
    BREAK;
   }
   }
    }
   }
}
 

 

 This is very easy to write, and then is to use the recursive method:

// determines whether palindromic recursive method
Import java.util.Scanner;
public class Testpalindrome1
{
 static void main public (String args [])
 {
   System.out.println ( "Please enter a character:");
   Scanner Scanner Scanner new new = (the System.in);
   String = scanner.nextLine STR ();
   IF (palindromeN ( STR, 0, str.length () -. 1))
   {
    System.out.println ( "string palindrome");
   }
   the else
   {
    System.out.println ( "string is not a palindrome");
   }
  
 
 }
 
 
 public static boolean palindromeN (String str, int a, int b) // a and b corresponding to the two pointers;
 {
  IF (A> = b)
  {
   return to true;
  }
  IF (str.charAt (A) == str.charAt (B))
  {
   return palindromeN (STR, ++ A, - B);
  }
  else
  {
   return false;  
  }
 
 }

 

 


 
 Comparison of head and tail and is decremented by each function call the original judgment, it is clear that using a recursive save a lot of code length than without recursion

Guess you like

Origin www.cnblogs.com/wind-and-sky/p/11586372.html