首页 > 解决方案 > 递归函数倒数4-> 0,然后倒数0> 4,如何停止倒数

问题描述

此代码的目的是确认字母 A 准确出现 4 次,但使用递归函数。我可以让它正确计数,但是一旦它开始离开递归堆栈,它就会 +1 而不是 -1(我认为是因为它正在离开堆栈)。

有没有更好的方法来处理这个问题,让我非常卡住。

    public class App {
    public static boolean isPresentNTimes(String sequence, char marker, int count) {
        System.out.println("This is the count: " + count);
        if (sequence.isEmpty() != true){
            if(sequence.charAt(0) == marker) {
                isPresentNTimes(sequence.substring(1), marker, count-1);
                System.out.println("The count is" + count);
            }
            
            else {
                isPresentNTimes(sequence.substring(1), marker, count);
            }
        }
        
        if (count == 4){
            return true;
        } else {
            return false;
        }
    }

     public static void main(String []args){
        String seq1 = "ABBAACBA";
        System.out.println(isPresentNTimes(seq1, 'A', 4));
     }
}

标签: javarecursionstack

解决方案


这就是你真正想要实现的:

public static boolean isPresentNTimes(String sequence, char marker, int count) {
    if(count < 0)
        return false;
    else if(count == 0 && sequence.isEmpty())
        return true;
    else if (!sequence.isEmpty()){
        if(sequence.charAt(0) == marker) {
            System.out.println("The count is " + count );
            count--;
        }
        return isPresentNTimes(sequence.substring(1), marker, count);
    }
    else
       return false;
}

count=4每次发现一个元素等于标记时,开始并递减。确保在每次递归调用之前添加 return(return isPresentNTimes(...)):

在您正在比较的代码中

  if (count == 4){
        return true;
    } else {
        return false;
    }

if count == 4,这没有意义,因为您已经从 count = 4 开始。


推荐阅读