713147. Count the Substring
Count the Substring
Slug: count-the-substring--170645
Difficulty: Hard
Id: 713147
Topic Tags: Strings, Dynamic Programming, Data Structures, Algorithms
Summary
The problem is to count the number of occurrences of a given substring within a larger string. This involves using dynamic programming techniques to efficiently solve the problem.
Detailed Explanation
To solve this problem, we can use dynamic programming to keep track of the number of occurrences of the substring at each position in the string. We initialize a 2D array dp where dp[i][j] represents the number of occurrences of the substring ending at index i and having length j.
We then iterate through the string, updating the dp array as we go. For each character, we check if it matches the first character of the substring. If it does, we increment the count of occurrences for that substring.
Here's a step-by-step breakdown:
- Initialize
dpwith zeros. - Iterate through the string:
- For each character, check if it matches the first character of the substring.
- If it does, update the count of occurrences for that substring by adding 1 to
dp[i][j].
- Return the total count of occurrences.
Time complexity: O(n * m), where n is the length of the string and m is the length of the substring.
Space complexity: O(n * m), since we need to store the dynamic programming table.
Optimized Solutions
Java
public int countSubstring(String str, String sub) {
int n = str.length();
int m = sub.length();
int[][] dp = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (str.charAt(i) == sub.charAt(j)) {
if (j == 0) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
} else {
dp[i][j] = 0;
}
}
}
int count = 0;
for (int i = 0; i < n; i++) {
if (dp[i][m - 1] > 0) {
count++;
}
}
return count;
}