java - 递归函数倒数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));
}
}
解决方案
这就是你真正想要实现的:
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 开始。
推荐阅读
- vba - 带有嵌入变量的 VBA 字符串
- c# - 如何使用 FileHelper 库获取分隔符的数量
- python - 如何使用不同参数模型的网格搜索和交叉验证?
- snowflake-cloud-data-platform - 如果复制文件时 S3 前缀不正确,如何接收错误?
- reactjs - 有没有函数的didmount方法?
- python-3.7 - 无法在 anaconda propmt windows 10 中的 python-3.7.0 版本中安装 xgboost
- gradle - gradle 6.x kotlin spring-boot jar 发布失败,需要 gradle-kotlin-dsl 中的解决方法
- c# - 除非使用异步,否则 Ok() 在当前上下文中不存在
- applescript - 如何在当前 Keynote 文档的当前幻灯片上选择一个特定图像?
- delphi - 跨 DLL 使用 Indy SMTP 和 HTTPS