首页 > 解决方案 > 返回字符串“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 循环,但我真的认为这也可以。

标签: javastringloopssubstring

解决方案


您将进入无限循环,因为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;
}

推荐阅读