java - 使用递归计算字符串中出现的 hi
问题描述
我遇到了这个问题:
给定一个字符串,递归(无循环)计算小写“hi”在字符串中出现的次数。
count Hi("xxhixx") = 1
count Hi("xhixhix") = 2
count Hi("hi") = 1
我运行我的代码,它运行良好,但有没有更好的方法呢?这是我的代码(提前谢谢你):
public int countHi(String string) {
int count =0;
return countHi(string,count);
}
public int countHi(String string, int count) {
if(string.length()==0)
return count;
else {
if(string.endsWith("hi"))
count++;
return countHi(string.substring(0, string.length()-1) , count);
}
}
解决方案
您不需要该参数,此外,您可以通过删除它们等于“hi”时count
的最后 2 个字符来减少递归调用的数量:String
public int countHi(String string) {
if(string.length() < 2) {
return 0; // no occurrences of "hi"
} else {
if(string.endsWith("hi")) {
// one occurrence + the occurrences in the substring of the first length-2 chars
return 1 + countHi(string.substring(0, string.length()-2));
} else {
// the occurrences in the substring of the first length-1 chars
return countHi(string.substring(0, string.length()-1));
}
}
}
推荐阅读
- powershell - CSV 输出不可读
- php - 在本地主机上使用表达式引擎并获得数据库错误
- html - 如何制作圆形背景?
- spring - Spring mvc sessionRegistry 返回空的委托人列表
- ansible - 如何生成具有范围的列表并将其保存在剧本的 var 中?
- java - 如何在 spring boot 中使用 thymleaf 和 Flying Saucer 准备 pdf 报告
- java - Spring Cache 将变量 int 配置为 @Cacheable 注释中的键
- python - 如何在 python List 上强制执行特定类型
- android - WorkManager 使用 setForegroundAsync() 和 ListenableWorker
- javascript - fullcalendar:未捕获的 TypeError:无法读取 null 的属性“nodeName”