To solve this problem, we need to count how many times a given substring appears in a main string. The approach involves checking each possible starting position in the main string where the substring could fit and counting the matches.
Approach
- Calculate Lengths: First, compute the lengths of the main string and the substring.
- Edge Case Handling: If the substring is longer than the main string, return 0 immediately as it can't appear.
- Iterate Through Possible Positions: Loop through all valid starting positions in the main string where the substring can fit. The valid starting positions range from 0 to
len(main_string) - len(substring)(inclusive). - Check for Matches: For each starting position, extract the substring of the same length as the target substring and compare it. If it matches, increment the count.
- Return Result: Return the total count of matches.
Solution Code
def count_substring(string, sub_string):
len_sub = len(sub_string)
len_str = len(string)
count = 0
# Iterate over all valid starting positions
for i in range(len_str - len_sub + 1):
if string[i:i+len_sub] == sub_string:
count += 1
return count
Explanation
- Length Calculation:
len_subis the length of the substring, andlen_stris the length of the main string. - Valid Positions: The loop runs from 0 to
len_str - len_sub(inclusive) becauserange(len_str - len_sub +1)gives all starting indices where the substring can fit (sincerangeis exclusive of the upper bound). - Match Check: For each starting index
i, we take the slicestring[i:i+len_sub]and compare it to the target substring. If they match, we increment the count.
This approach efficiently checks all possible positions and ensures we count all occurrences of the substring, including overlapping ones (like "AA" in "AAAA" which appears 3 times).
The time complexity is O(n*m) where n is the length of the main string and m is the length of the substring (due to string comparns), but this is optimal for small to medium-sized strings as required by typical problem constraints.
Example Usage:
- Input:
string = "ABCDCDC", sub_string = "CDC"→ Output:2 - Input:
string = "AAAA", sub_string = "AA"→ Output:3 - Input:
string = "Hello", sub_string = "World"→ Output:0
This solution handles all these cases correctly.


作者声明:本文包含人工智能生成内容。