Java用递归查找某个字符串在另一个字符串中出现的次数

Complete the method numXY.
It finds the number of times the string "XY" appears in the input string recursively.
You must not use any loops or regular expressions.
Test cases:
numXY("AAXYAA") → 1
numXY("AXYBXYAA") → 2

格式:
public static int numXY(String input) {

// base case



// recursive step

}

提供一个思路,代码和注释在下面

public static int numXY(String input) {
        String XY = "XY";
        // base case
        // 被查找的字符串为null的话,出现次数肯定为0,终止递归
        if (input == null){
            return 0;
        }
        // 如果字符串长度已经小于待查找的字符串了,说明出现次数为0,终止递归
        if(input.length() < XY.length()){
            return 0;
        }
        // count记录了被查找的字符串是否以XY开头,0不是,1是
        int count = 0;
        if (input.startsWith(XY)){
            count++;
        }
        // recursive step
        // 从第二个字符开始的子字符串进行递归
        return numXY(input.substring(1)) + count;
    }

参考下这个


public class Main {
    public static void main(String[] args) {
        System.out.println(numberOf("https://www.cjavapy.com", 'a'));
    }
    static int numberOf(String text, char characterToCount) {
        return helper(text, characterToCount, 0);
    }
    static int helper(String text, char charToCount, int index) {
        if (text.isEmpty() || index == text.length()) return 0;
        int countCharOnRight = helper(text, charToCount, index+1);
        return (text.charAt(index) == charToCount) ? 1 + countCharOnRight : countCharOnRight;
    } 
}

实现步骤和详细代码如下:

  • 定义一个名为 numXY 的方法,该方法带有一个字符串类型的输入参数 input。
  • 在方法中,首先检查字符串 input 的长度是否小于 2。如果是,则返回 0,因为字符串 "XY" 必须至少包含两个字符。这就是递归的基本情况。
  • 如果 input 的长度大于等于 2,则检查第一个字符和第二个字符是否分别为 "X" 和 "Y"。如果是,则递归调用 numXY 方法,并将 input 的第三个字符开始的子字符串作为参数传递。然后将返回值加 1。
  • 如果第一个字符和第二个字符不是 "X" 和 "Y",则递归调用 numXY 方法,并将 input 的第二个字符开始的子字符串作为参数传递。然后将返回值返回。
public static int numXY(String input) {
    // base case
    if (input.length() < 2) {
        return 0;
    }
    
    // recursive step
    if (input.charAt(0) == 'X' && input.charAt(1) == 'Y') {
        return 1 + numXY(input.substring(2));
    } else {
        return numXY(input.substring(1));
    }
}

功能效果

int num1 = numXY("AAXYAA"); // num1 will be 1
int num2 = numXY("AXYBXYAA"); // num2 will be 2
int num3 = numXY("XYXYXY"); // num3 will be 3