zoukankan      html  css  js  c++  java
  • 使用递归判断回文

    使用递归方式判断某个字串是否是回文(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;
     }
    }

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

  • 相关阅读:
    一个人的旅行 dij(),评测的时候有点惨
    CodeFroce Round 340 div2 E XOR and Favorite Number【莫队算法】
    [HihoCoder-1185] 连通性·三 【tarjan+缩点】
    2017百度之星初赛(A)1001,1005,1006解题报告
    HDU 5961&AOJ 821 传递
    pair
    优先队列 priority_queue
    ccf 201903-5
    memset 和 fill 的区别
    ccf 20190302
  • 原文地址:https://www.cnblogs.com/dd110343/p/11581428.html
Copyright © 2011-2022 走看看