First, determine whether a string is a palindrome, implemented by recursive method.
Second, the general idea:
1, an input character string;
2, to compare the corresponding character string stored in the character array before and after then;
3, until the meet last remaining one or zero characters, is a palindrome;
Third, the source code:
1 package org.yuan.Day2; 2 3 import java.util.Scanner; 4 5 public class Palindrome { 6 7 public static void main(String[] args) { 8 System.out.println("请输入一个字符串:"); 9 Scanner sc=new Scanner(System.in); 10 String s = sc.next(); 11 boolean huiwen = palindrom(s, 0 , s.length() ); 12 System.out.println(huiwen); 13 sc.close(); 14 } 15 public static Boolean palindrom (S String, int I, int length) { 16 IF (length-2. 1 == * I-2 * I || length == 0 ) . 17 return to true ; // if satisfied to the last The number of remaining characters is 1 or 0, it is a palindromic 18 is IF ((s.toCharArray () [I]! = s.toCharArray () [I-length-1]) || (I> = 1 length- -i)) { // the string into a character array, before and after the corresponding characters are equal . 19 return to false ; 20 is } 21 is return palindrom (S, I ++, length); // recursive 22 } 23 } 24
IV Summary:
That calls itself recursively, repeat the same steps, but there are restrictions can to end this recursive function. Recursion can be a complex problem into a small problem, greatly reducing the amount of code.