- Topic Introduction:
"Palindrome" is the correct reading, the opposite of reading all the same sentence. For example, "Who am I that I" using a recursive algorithm to detect palindrome algorithm is described as follows:
A single or zero-character string is a palindrome.Any other string is a palindrome if the first and last characters are
the same, and the string that remains, excepting those characters, is a palindrome.
- Design ideas:
1. Analyzing string length (n), i.e., when 1 is 0 with a string of palindromes.
1 and 2. If not match, then we need to string recursive determination, i.e., to get the first (n-1) characters of a (length-n) characters are compared, if the same is n-1, then comparison, so the cycle, there will be an end point.
3. The end point is when n is 0 or 1, i.e. if this is a palindrome.
4. recursive condition is: if the first (n-1) characters of a (length-n) identical characters, the string length - 1, not satisfied, then exit.
- code show as below
package javatask; import java.util.Scanner; public class Palindrome { static Scanner in=new Scanner(System.in); static char str[] = new char[99]; public static void main(String [] args) { System.out.println("请输入字符串"); String a; a=in.next(); if(Palindrome(a,a.length()))//如果是回文 System.out.println("It's a palindrome"); The else // if not palindromic System.out.println ( "Not It apos Palindrome A" ); } static public Boolean Palindrome (A String, int n-) { int length = a.length (); IF (n-== n-== 0 ||. 1 ) return to true ; the else { IF (a.charAt (. 1-n-) == a.charAt (n--length)) // the first character to the last character comparison return Palindrome (a, --n); // recursive repeatedly determines the else return to false ; //Not a palindrome } } }
- Screenshot operating results
- Programming summary analysis
This question is more difficult point of it is to use recursion to determine how and how to extract a character in a string operation.