LeetCode第28题代码无法通过特定测试用例,请求排查原因
LeetCode第28题代码在特定测试用例失败的问题分析与修复
问题背景
刚接触编程,正在解决LeetCode第28题「找出字符串中第一个匹配项的下标」。本地VS Code运行代码能返回预期结果,但在LeetCode平台上无法通过第15个测试用例:输入haystack为"mississippi",needle为"issip"。尝试过断点调试和AI工具,仍未找到问题。
题目要求
给定两个字符串needle和haystack,返回needle在haystack中首次出现的下标,若不存在则返回-1。
示例
- 输入: haystack = "sadbutsad", needle = "sad" → 输出: 0
- 输入: haystack = "leetcode", needle = "leeto" → 输出: -1
原始代码
public int StrStr(string haystack, string needle) { if (needle == haystack) { return 0; } if (needle.Count() > haystack.Count()) { return -1; } int currentIndex = 0; int i = 0; int target = needle.Count(); int seeIfAtTarget = 0; string tempString = needle; //goes through the main word foreach (char letterInMainWord in haystack) { //if the letter is the same as the first letter of the comparison if (letterInMainWord == needle[0]) { currentIndex = i; //loops through the letters in the compared word foreach (char letter in tempString) { //adds one to seeIfAtTarget, and we will check to see if that meets the target if (letter == haystack[currentIndex]) { seeIfAtTarget++; currentIndex++; } else { seeIfAtTarget = 0; break; } if (seeIfAtTarget == target) { return i; } } } i++; } return -1; }
问题分析
你的代码存在两个关键问题,导致测试用例失败:
索引越界异常
遍历haystack时未限制i的范围,当i的位置使得i + needle.Length > haystack.Length时,剩余字符数量不足以匹配needle,但代码仍会进入内部匹配循环,导致currentIndex超出haystack的索引范围,抛出IndexOutOfRangeException。比如在目标测试用例中,当i=7时,currentIndex会递增到11,而haystack的最大索引是10,触发异常导致LeetCode判定不通过。匹配计数未及时重置
seeIfAtTarget变量仅在匹配失败时设为0,若某次部分匹配后未触发else分支(比如循环正常结束但未完成全匹配),该变量会保留之前的计数,可能导致后续匹配逻辑错误。
此外,代码未处理needle为空字符串的边界情况,不符合题目要求(空字符串应返回0)。
修复后的代码
public int StrStr(string haystack, string needle) { // 处理空字符串边界情况 if (string.IsNullOrEmpty(needle)) { return 0; } int haystackLen = haystack.Length; int needleLen = needle.Length; if (needleLen > haystackLen) { return -1; } // 限制遍历范围:仅检查可能匹配的位置 for (int i = 0; i <= haystackLen - needleLen; i++) { // 首字符不匹配直接跳过,提升效率 if (haystack[i] != needle[0]) { continue; } int matchCount = 0; // 逐字符匹配 for (int j = 0; j < needleLen; j++) { if (haystack[i + j] == needle[j]) { matchCount++; } else { break; } } // 全匹配则返回当前下标 if (matchCount == needleLen) { return i; } } return -1; }
修复说明
- 新增空字符串处理逻辑,符合题目边界要求;
- 使用
for循环替代foreach,直接控制遍历范围到haystackLen - needleLen,彻底避免索引越界; - 每次匹配前重置
matchCount,确保计数准确; - 通过
i+j直接计算匹配字符的下标,简化逻辑; - 先检查首字符是否匹配,快速过滤不可能的情况,提升代码效率。
测试目标用例时,当i=4会触发全匹配,返回正确结果4。
内容的提问来源于stack exchange,提问作者user23641408
相关产品推荐
相关产品推荐

