回文序列判断

判断回文序列

一,题目:递归判断输入的字符串是否为回文字符串。

 1 import java.util.Scanner;
 2 public class Test {
 3     private static int count;
 4     public static void main(String[] args) {
 5         Scanner in=new Scanner(System.in);//输入
 6         String str=in.next();
 7         count=str.length();//私有数据count储存长度这个定值
 8         f(str,count);
 9     }
10     public static void f(String s,int l) {//l作为判断递归终止的条件
11         char s1,s2;
12         if(l==count/2||l==count/2+1)//如果l为字符串长度的一半
13             System.out.println("该字符串是回文串");
14         else{//判断首尾
15             s1=s.charAt(l-1);//记录尾位置
16             s2=s.charAt(count-l);//记录首位置
17             if(s1==s2) {//如果相等,则记录位置的l变量自减,继续递归
18                 l--;
19                 f(s,l);
20             }
21             else//否则取消递归
22                 System.out.println("该字符串不是回文串");
23         }
24     }
25 }

 2019-09-24  19:31:48

后期运行发现上述代码因为巧合避免了一些已经忽略的问题,上因为采用的返回值类型为void类型 ,思路有所不同。

下面为Boolean类型的代码

 1 import java.util.Scanner;
 2     public class palindrome {
 3         public static boolean  recurrence(String s,int len,int n){//定义递归函数 字符串,长度,首元素序号
 4             if(len<=1||len==s.length()/2||len==(s.length()+1)/2) {//终止条件
 5                 return true;
 6             }
 7             else {
 8                 if(s.charAt(n)==s.charAt(len-1)) 
 9                 return recurrence(s,--len,++n);
10             }
11             return false;
12         }
13             
14     public static void main(String[] args) {
15         Scanner in = new Scanner(System.in);
16         String s1 = in.next();
17         boolean k=recurrence(s1,s1.length(),0);
18         System.out.println(k);
19       }
20 
21 }

需要多多比较,巩固学习。

原文地址:https://www.cnblogs.com/dongao/p/11575131.html