【发布时间】:2021-05-01 19:39:43
【问题描述】:
此代码的目的是确认字母 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));
}
}
【问题讨论】: