内容中心

2026年靠谱的汽车扎带实力厂家推荐-浙江力泰塑料有限公司

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

  1. Calculate Lengths: First, compute the lengths of the main string and the substring.
  2. Edge Case Handling: If the substring is longer than the main string, return 0 immediately as it can't appear.
  3. 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).
  4. 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.
  5. 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_sub is the length of the substring, and len_str is the length of the main string.
  • Valid Positions: The loop runs from 0 to len_str - len_sub (inclusive) because range(len_str - len_sub +1) gives all starting indices where the substring can fit (since range is exclusive of the upper bound).
  • Match Check: For each starting index i, we take the slice string[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.

浙江力泰塑料有限公司

浙江力泰塑料有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?