测试用例未通过,求排查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
- 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 whenindexis-1. - Wrong position update for next search: The line
i = i + text.indexOf(pattern, index) + pattern.length();is flawed. Whenindexis-1,text.indexOf(pattern, index)returns0(since searching from-1starts at the beginning), causing an infinite loop or skipping valid overlapping matches. - 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 jumpspattern.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 + 1instead ofcurrentIndex + patternLength, we ensure we don't skip overlapping pattern matches (like the"aba"in"abababa"). - Safe character access: We check if
nextCharPositionis 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
相关产品推荐
相关产品推荐

