Count Pattern Occurrences (Overlapping)

easy Strings

Problem

Two words are given: a text and a pattern. Print how many times the pattern appears in the text. Overlapping matches count: aa appears 3 times in aaaa.

Constraints

  • 1 <= lengths <= 5000

Examples

Input

aaaa aa

Output

3

Solutions

Best approachTime O(n * m)Space O(1)

Methods like String.split or replace count non-overlapping matches only. Moving the start by one position after each match counts the overlapping ones too.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count matches.
 * Input   : A text and a pattern.
 * Output  : The number of matches.
 * Approach: Try each start.
 * Time    : O(n * m)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(String a, String b) {
        // Step 1: Try every start position where the pattern can still fit inside the text.
        int count = 0;
        for (int start = 0; start + b.length() <= a.length(); start++) {
            // Step 2: regionMatches compares the pattern with the part of the text that begins at start.
            if (a.regionMatches(start, b, 0, b.length())) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. Why does aa appear 3 times in aaaa?