回文串判断(递归实现)

  目的:判断一个字符串是否为回文串。

  代码如下:

 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         else{
29             System.out.println("该字符串不回文");
30         }
31     }
32 
33 }

judge方法的3个参数:String a指输入的字符串;int b初始为字符串头部的下标,每执行一次方法自增一次;int c初始为字符串尾部的下标,每执行一次方法自减一次。

具体执行:利用charAt读取字符串中的字符,分别用变量c1和c2表示,之后进行比较。中止条件为c==b(当字符串长度为偶数)或c==b+1(字符串长度为奇数),不符合中止条件,且c1==c2则递归调用方法。直至出现结果。

猜你喜欢

转载自www.cnblogs.com/20183711PYD/p/11575580.html