技术实现需求:统计子串出现次数及最长连续重复子串次数
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.
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()withcurrentIndex += 1.
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:
核心思路
- 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).
- For each substring length, check the input string to find how many times a substring of that length repeats consecutively.
- 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

