使用递归判断回文

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

“回文”是指正着读、反着读都一样的句子。比如“我是谁是我”
使用递归算法检测回文的算法描述如下:
A single or zero-character string is a palindrome.
Any other string is a palindrome if the first and last characters are the same, and the string that remains, excepting those characters, is a palindrome.

   看到这个问题,首先我想到递推可以用来判断首位字符与末位字符是否相等,并且字符串长度为0或1时直接可以判断为回文,于是我将字符串转化为一个字符数组,通过for循环来进行首尾判断,产生了以下代码:

package judge;
import java.util.Scanner;
public class Palindrome {
 static Scanner sc=new Scanner(System.in);
 public static void main(String[] args) {
  System.out.println("请输入字符串:");
  String a=sc.next();
  boolean tf=huiwen(a,0,a.length());
  System.out.println(tf);
 }
 public static boolean huiwen(String a,int low,int length) {
  if(length==0||length==1)
   return true;
  else if(a.toCharArray()[low]==a.toCharArray()[length-1]) 
   return huiwen(a,low+1,length-1);
  return false;
 }
}

 

 

 通过此次编程,我可以熟练的运用递归方法了,在编程速度方面我还是比较慢,以后还要多加练习,将自己的代码编写速度提上去。

 

posted @ 2019-09-24 21:58  土豆面包  阅读(403)  评论(0)    收藏  举报