• 课堂测试:使用递归方式判断回文


    1.设计思想:利用boolean函数,以及递归算法,如果没有字符或只有一个字符,就返回true,利用charAt判断对应位置的字符是否相等,主函数中调用函数,实现判断。

    2.源程序代码:

    package Palindrome;
    import java.util.Scanner;
    import java.lang.String;
    public class Testp {
     public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      String str = scanner.next();
      boolean t = Test(str,0,str.length()-1);
      if(Test(str,0,str.length()-1))
       System.out.println("该字符串是回文。");
      else {
       System.out.println("该字符串不是回文。");
      }
     }
     public static boolean Test(String a,int f,int l) {
      char ch1;
      char ch2;
      if(a.length()==0||a.length()==1) {
       return true;
      }
      ch1 = a.charAt(f);
      ch2 = a.charAt(l);
      if(ch1==ch2&&f<=l) {
       return true;
      }
      if(ch1!=ch2) {
       return false;
      }
      return Test(a,f+1,l-1);
     }
     
    }
    3.运行结果截图
     
     
    4.总结分析:递归算法就是不断的调用自身解决问题,而且必须有循环终止条件,递归算法非常简洁,但是运行效率相对较低。
  • 相关阅读:
    套题 8.22
    套题 8.21
    P1042 乒乓球
    套题8.20
    #52. 【UR #4】元旦激光炮 (交互式题)
    #82. 【UR #7】水题生成器
    度度熊与邪恶大魔王
    wpf 获取image控件的图片并保存
    wpf 让正执行的程序暂停几秒钟
    wpf问题集锦
  • 原文地址:https://www.cnblogs.com/Lhxxx/p/11582945.html
Copyright © 2020-2023  润新知