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

测试用例未通过,求排查Java字符串模式匹配代码问题

Fixing getCharsThatFollowPattern to Handle Overlapping Patterns & Correct Termination

Let's break down the issues in your code and fix them to pass both test cases:

Key Problems in Your Current Code

  1. Incorrect loop termination: Your while (i <= text.length()) condition doesn't check if the pattern was actually found (index != -1). This leads to unnecessary iterations and potential invalid character access when index is -1.
  2. Wrong position update for next search: The line i = i + text.indexOf(pattern, index) + pattern.length(); is flawed. When index is -1, text.indexOf(pattern, index) returns 0 (since searching from -1 starts at the beginning), causing an infinite loop or skipping valid overlapping matches.
  3. No handling of overlapping patterns: For test case (a), the pattern "aba" overlaps in "abababa" (positions 0, 2, 4). Your code skips these overlaps because it jumps pattern.length() positions each time.

Fixed Code

Here's the corrected version that addresses all these issues:

public static ArrayList<Character> getCharsThatFollowPattern(String text, String pattern) {
    ArrayList<Character> characters = new ArrayList<>();
    int patternLength = pattern.length();
    int currentIndex = text.indexOf(pattern);

    while (currentIndex != -1) {
        int nextCharPosition = currentIndex + patternLength;
        // Only add the character if the pattern isn't at the very end of the text
        if (nextCharPosition < text.length()) {
            characters.add(text.charAt(nextCharPosition));
        }
        // Move to the next character after the current match to allow overlapping patterns
        currentIndex = text.indexOf(pattern, currentIndex + 1);
    }

    return characters;
}

How This Fix Works

  • Proper loop termination: We only continue looping as long as currentIndex (the position of the pattern) is not -1 (meaning the pattern was found).
  • Overlap support: By starting the next search at currentIndex + 1 instead of currentIndex + patternLength, we ensure we don't skip overlapping pattern matches (like the "aba" in "abababa").
  • Safe character access: We check if nextCharPosition is less than the text length before accessing the character, avoiding out-of-bounds errors and ensuring we only add characters for non-ending pattern occurrences.

Testing the Fixed Code

  • Test Case (a): For "abababa" and "aba", the code finds matches at positions 0, 2, and 4. It adds the characters at positions 3 ('b') and 5 ('b'), returning [b, b] as expected.
  • Test Case (b): For "abcabdabcab" and "ab", matches are at 0, 3, 6, 9. It adds characters at 2 ('c'), 5 ('d'), 8 ('c'), returning [c, d, c] as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:11:15