zoukankan      html  css  js  c++  java
  • 递归方法

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

    public static void main(String[] args) {
        System.out.println("please input a string of Characters:");
        Scanner input=new Scanner(System.in);
        String str=input.nextLine();
        input.close();
        int n=0;
        int m=str.length()-1;
        //boolean p= huiWen(str,n,m);
        if(huiWen(str,n,m))
        System.out.println("这个字符串是回文字符串");
        else
        System.out.println("这个字符串不是回文字符串");
        }
        
        public static boolean huiWen(String str,int n,int m){
            if(n > m)
                throw new IllegalArgumentException();
            if(n == m)
                return true;
            else{
                return (str.charAt(n) == str.charAt(m)) && huiWen(str,n+1,m-1);
            }
    
    
        }

    思路:

    先定义一个判断回文的方法,先得到字符串的长度,利用charAt方法去比较第一个和最后一个字符,如果一样,前一个向后移一位,后一个向前移一位,再比较;如此下去,直到前一个等于后一个;

    在主方法中调用这个方法,进行判断;

    问题:

    只能判断字符个数为奇数的字符串,偶数的出现问题;

  • 相关阅读:
    软件工程—附加作业
    软件工程最终总结
    电梯调度(两人结对)
    VS单元测试
    第二周作业(2,3题)
    VS的安装
    补救
    漂亮男孩不说谎
    博客带我成长
    Java后缀数组-求sa数组
  • 原文地址:https://www.cnblogs.com/KYin/p/9788364.html
Copyright © 2011-2022 走看看