如何使用递归计算更大数组中子数组的数量

How to count the number of subarrays within a bigger array using recursion

如何在不使用 copyOfRange 的情况下递归地从更大的数组中获取子数组?

例如,如果 int[] a = {1,2,1,3,1,2,1,1,2}int[] b = {1,2},则正确答案为 3。 这是我唯一的递归调用,但我不确定除此之外还能做什么。 我知道基本情况应该是 if(a.length < b.length),但我不知道如何计算出现次数。 函数 returns return numSubstring(a,b,low, mid-1) + numSubstring(a,b, mid+1,high);

public static int countSubs(int [] data, int [] sub) {
    int cnt = 0;
    if (data.length < sub.length) {
        return cnt;
    }
    boolean found = true;
    for (int i = 0; i < sub.length; i++) {
        if (data[i] != sub[i]) {
            found = false;
            break;
        }
    }
    if (found) {
        cnt++;
    }
    
    cnt += countSubs(Arrays.copyOfRange(data, 1, data.length), sub);
    return cnt;
}