Suppose we have a string s and a substring t. We have to count how many times t occurs in s.
So, if the input is like s = "abaabcaabababaab", t = "aab", then the output will be 3 because the substrings are ab(aab)c(aab)abab(aab).
To solve this, we will follow these steps −
- cnt := 0
- for i in range 0 to (size of s - size of t), do
- if substring of s[from index i to i + size of t - 1] is same as t, then
- cnt := cnt + 1
- if substring of s[from index i to i + size of t - 1] is same as t, then
- return cnt
Example
Let us see the following implementation to get better understanding
def solve(s, t): cnt = 0 for i in range(0, len(s) - len(t) + 1): if s[i:i + len(t)] == t: cnt = cnt + 1 return cnt s = "abaabcaabababaab" t = "aab" print(solve(s, t))
Input
"abaabcaabababaab", "aab"
Output
3