首页 > 技术文章 > 判断回文

znjy 2020-10-03 21:18 原文

要求:判断字符串是否是回文字符串

 1 package com.test;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test {
 6     static String s = new String();
 7     static int len = 0;
 8     static int k;
 9 
10     public static void f(int i, int j) {
11         if (i == k && s.charAt(i) == s.charAt(j))// 判断结束的条件
12         {
13             System.out.println("是回文");
14             return;
15         }
16 
17         if (s.charAt(i) == s.charAt(j))// 若满足则进行下一步的递归
18             f(i + 1, j - 1);
19         else// 若不满足则输出
20         {
21             System.out.println("不是回文");
22             return;
23         }
24     }
25 
26     public static void main(String[] args) {
27         // TODO Auto-generated method stub
28         System.out.println("请输入字符串:");
29         Scanner in = new Scanner(System.in);
30         s = in.nextLine();
31         int k = 0;
32         len = s.length();// 获取字符串长度
33         if (len % 2 == 0)// 通过奇偶个数来找到中间值
34             k = len / 2 - 1;// 找到中间的下标
35         else
36             k = len / 2;// 找到中间的下标
37         if (len == 1 || len == 0)// 若是空串或只有一个字符
38             System.out.println("是回文");
39         else {
40             f(0, len - 1);// 递归计算
41         }
42     }
43 }

推荐阅读