首页 > 解决方案 > 使用递归计算字符串中出现的 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);
    }
}

标签: javarecursion

解决方案


您不需要该参数,此外,您可以通过删除它们等于“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));
        }
    }
}

推荐阅读