java - 返回字符串“hi”在给定字符串中出现的次数
问题描述
我编写了以下 Java 代码,它返回了超时错误。我不完全确定这意味着什么,也不知道为什么代码不运行
public int countHi(String str) {
int pos = str.indexOf("hi");
int count = 0;
while(pos!=-1)
{
count++;
pos = str.substring(pos).indexOf("hi");
}
return count;
}
我知道另一种解决方案,使用 for 循环,但我真的认为这也可以。
解决方案
您将进入无限循环,因为pos
永远不会超过第一个匹配项,因为第一个匹配项将包含在子字符串中。
indexOf()
您可以通过在while
循环中使用此覆盖版本来修复:
pos = str.indexOf("hi", pos + 1);
或者使用do... while
循环来避免重复调用indexOf()
:
public static int countHi(String str) {
int pos = -1, count = -1;
do {
count++;
pos = str.indexOf("hi", pos + 1);
} while (pos != -1);
return count;
}
推荐阅读
- swift - TabView 项目点击滚动到它的 NavigationView 顶部
- python - FastAPI:如何将任意属性 dict 映射到 pydantic 模型以让 swagger 显示细节
- java - java.io.FileNotFoundException:/opt/tomcat/conf/tomcat-users.xml(打开的文件太多)
- r - stat_cor:显示 r 值、p 值和显着性(***、**、*)
- javascript - 如何更改开发位置?
- python - 计算分位数的差异
- reactjs - React Native 视频最终出现白屏并且应用程序没有响应
- javascript - 如何发送位于另一个文件中的嵌入?
- ldap - OpenLDAP 副本在同步时跳过几个项目的原因可能是什么
- javascript - 名称中有空格的反应本机图像未加载