回文

题目:使用递归方式判断某个字串是否是回文( palindrome )

源代码:

 1 import java.util.Scanner;
 2 
 3 public class huiwen {
 4     public static boolean judge(String str,int n) {
 5         char a = str.charAt(n-1);
 6         char b = str.charAt(str.length()-n);
 7         System.out.print(a);
 8         System.out.println(b);
 9         if(n <= 1) {
10             return true;
11         }
12         else {
13             if(a == b) {
14                 return judge(str,n-1);
15             }
16             else {
17                 return false;
18             }
19         }
20     }
21     
22     
23     public static void main(String arsg[]) {
24         Scanner input=new Scanner(System.in);
25         String a = new String();
26         System.out.println("请输入字符串:");
27         a = input.next();   //输入字符串
28         boolean flag;
29         if(a.length() == 0) {
30             System.out.println("该字符串为回文");
31         }
32         flag = judge(a,a.length());
33         if(flag == true) {
34             System.out.println("该字符串为回文");
35         }
36         else if(flag == false){
37             System.out.println("该字符串不为回文");
38         }
39     }
40 }
41     

程序截图:

 思想:首先需要输入字符串,并对每个字符进行采集,然后运用递归思想,对收尾字符进行比较,若相同,便继续,若不同,便退出。在主函数中对返回值进行if判断,输出结果。

原文地址:https://www.cnblogs.com/fwk123/p/11582717.html