内容中心

2026年评价高的水利智慧灌区系统服务综合评价公司-四川鸿达安视科技有限公司

To solve this problem, we need to find the shortest substring that repeats to form the entire given string. If no such substring exists, we return the original string.

Approach

  1. Understand the Problem: We need to find the smallest length k such that the string can be divided into m equal parts (where m = length of string / k), and all parts are identical.
  2. Check Divrs: For each possible k from 1 to half the length of the string (since k must be a divr of the string length to form equal parts):
    • If k divides the string length, check if repeating the substring of length k (starting from the beginning) m times equals the original string.
  3. Return Result: If such a k is found, return the substring of length k. If no such k exists, return the original string.

Solution Code

def shortest_repeating_substring(s):
    n = len(s)
    for k in range(1, n // 2 + 1):
        if n % k != 0:
            continue
        substring = s[:k]
        if substring * (n // k) == s:
            return substring
    return s

# Example usage:
print(shortest_repeating_substring("abcabcabc"))  # Output: "abc"
print(shortest_repeating_substring("ababab"))     # Output: "ab"
print(shortest_repeating_substring("abcd"))       # Output: "abcd"

Explanation

  • Divr Check: For each k (from 1 to half the string length), we first check if k divides the string length. This ensures that the string can be split into equal parts of length k.
  • Repeating Substring Check: For valid k, we take the substring of length k from the start of the string and repeat it m times (where m = n/k). If this repeated substring equals the original string, we return it immediately (since we are checking from the smallest k first).
  • Edge Cases: If the string length is 1, the loop doesn't run, so we return the original string. For non-repeating strings (like "abcd"), no valid k is found, so we return the original string.

This approach efficiently finds the shortest repeating substring with a time complexity of O(n*d), where d is the number of divrs of the string length. This is optimal for most practical cases.

四川鸿达安视科技有限公司

四川鸿达安视科技有限公司



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

在线客服

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