You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术实现需求:统计子串出现次数及最长连续重复子串次数

Hey there! Let's tackle these two string-related problems step by step—they might seem similar at first glance, but the second one has a unique twist that sets it apart from standard substring counting.


需求1:统计字符串中指定子串的出现次数

This is a classic problem, and the approach depends on whether you want to count overlapping occurrences or not. Let's cover both scenarios:

核心思路

We'll iterate through the main string, checking for matches with the target substring. Each time we find a match, we increment our count and move our starting index forward (either by the substring length to avoid overlaps, or by 1 to include them).

Java实现代码

public static int countSubstringOccurrences(String mainStr, String subStr) {
    // Edge cases: empty substring or main string shorter than substring
    if (subStr.isEmpty() || mainStr.length() < subStr.length()) {
        return 0;
    }
    
    int count = 0;
    int currentIndex = 0;
    
    while ((currentIndex = mainStr.indexOf(subStr, currentIndex)) != -1) {
        count++;
        // Use subStr.length() for non-overlapping counts, change to 1 for overlapping
        currentIndex += subStr.length();
    }
    
    return count;
}

注意事项

  • If you need to count overlapping instances (e.g., counting "aa" in "aaaa" as 3 instead of 2), just replace currentIndex += subStr.length() with currentIndex += 1.

需求2:找出字符串中任意未预定义子串的最长连续重复次数

This one's trickier because we don't know what substring we're looking for—we need to scan for any substring that repeats consecutively the most times. Let's break this down:

核心思路

  1. Iterate over all possible substring lengths (from 1 up to half the length of the input string; a substring longer than half the input can only repeat once at most).
  2. For each substring length, check the input string to find how many times a substring of that length repeats consecutively.
  3. Keep track of the maximum consecutive repeat count we find.

Java实现代码(符合要求的方法)

public static int countWordsOccurence(String line) {
    // Handle null or empty input
    if (line == null || line.isEmpty()) {
        return 0;
    }
    
    int maxConsecutiveCount = 1;
    int strLength = line.length();
    
    // Check all possible substring lengths
    for (int subLength = 1; subLength <= strLength / 2; subLength++) {
        int startPos = 0;
        
        while (startPos <= strLength - subLength) {
            String currentSub = line.substring(startPos, startPos + subLength);
            int currentCount = 1;
            int nextCheckPos = startPos + subLength;
            
            // Count consecutive repeats of the current substring
            while (nextCheckPos + subLength <= strLength 
                   && line.substring(nextCheckPos, nextCheckPos + subLength).equals(currentSub)) {
                currentCount++;
                nextCheckPos += subLength;
            }
            
            // Update max count if current is larger
            if (currentCount > maxConsecutiveCount) {
                maxConsecutiveCount = currentCount;
            }
            
            // Jump to the end of the current repeated sequence to avoid redundant checks
            startPos = nextCheckPos;
        }
    }
    
    return maxConsecutiveCount;
}

示例验证

  • For input "raacdrunrunruntryingtotrackrunrun", the method finds "run" repeating 3 times consecutively, so it returns 3.
  • For input "baabugbugbackscarybugbugbug", it detects "bug" repeating 3 times in a row, so the result is 3.

性能说明

This implementation runs in O(n²) time, which is efficient enough for most practical use cases. If you're working with extremely long strings, you could optimize using algorithms like KMP or suffix arrays, but this version is straightforward and easy to debug.


内容的提问来源于stack exchange,提问作者Tom ros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:05:48