Objective: to determine whether a string is a palindrome sequence.
code show as below:
1 import java.util.Scanner; 2 3 public class Palindrome { 4 public static void main(String[] args) { 5 Scanner in = new Scanner(System.in); 6 String s = in.next(); 7 int n = s.length(); 8 if(n == 1||n == 0){ 9 System.out.println("该字符串回文"); 10 } 11 else{ 12 judge(s,0,n-1); 13 } 14 in.close(); 15 } 16 17 public static void judge(String a, int b, int c){ 18 char c1 = a.charAt(b); 19 char c2 = a.charAt(c); 20 if(c1==c2){ 21 if(c == b||c == b+1){ 22 System.out.println("该字符串回文"); 23 } 24 else{ 25 judge(a,++b,--c); 26 } 27 } 28 the else { 29 System.out.println ( "the string does not palindromes" ); 30 } 31 } 32 33 is }
Method judge three parameters: String a character string input means; int b initially subscript string head, the method is performed once per time increment; int c subscript as an initial end of the string, the method is performed once per decrement once.
Specific implementation: the use of charAt read character string, respectively represent variables c1 and c2, then compared. Abort condition c == b (when the string length is an even number) or c == b + 1 c1 == c2 recursively calling the method (length of the string is odd), the suspension does not meet the conditions, and. Until the results.