JavaScript最宽牧场索引返回函数调试问题求助
解决思路与修正代码
你不需要完全重写代码,只需要调整逻辑,在遇到长度相同的牧场时,更新记录为更靠后的那个即可。核心思路是遍历字符串时跟踪当前牧场的起始位置和长度,每次遇到分隔符('-')或遍历结束时,将当前牧场与已记录的最大牧场比较:
- 若当前牧场更长,更新最大牧场信息
- 若当前牧场长度等于最大长度,也更新最大牧场信息(因为要保留最后出现的)
- 全为分隔符时返回
[0,0,0]
修正后的代码
function widestPasture(str) { let maxLength = 0; let startIdx = 0; let endIdx = 0; let currentStart = null; let currentLen = 0; for (let i = 0; i < str.length; i++) { const char = str[i]; if (char === '_') { if (currentStart === null) { currentStart = i; } currentLen++; } else { if (currentLen > 0) { // 比较当前牧场与最大牧场 if (currentLen > maxLength) { maxLength = currentLen; startIdx = currentStart; endIdx = i - 1; } else if (currentLen === maxLength) { // 长度相同时,更新为更靠后的牧场 startIdx = currentStart; endIdx = i - 1; } // 重置当前牧场跟踪变量 currentStart = null; currentLen = 0; } } } // 处理字符串以牧场结尾的情况 if (currentLen > 0) { if (currentLen > maxLength) { maxLength = currentLen; startIdx = currentStart; endIdx = str.length - 1; } else if (currentLen === maxLength) { startIdx = currentStart; endIdx = str.length - 1; } } // 全为分隔符的情况 if (maxLength === 0) { return [0, 0, 0]; } return [maxLength, startIdx, endIdx]; }
测试验证
- 输入
"_-___-__-____-______-_"返回[6,14,19],符合要求 - 输入
"_-___-__-___-"返回[3,9,11],正确保留最后一个等长牧场 - 输入
"---"返回[0,0,0],处理全分隔符场景
内容的提问来源于stack exchange,提问作者AtomicCow
相关产品推荐
相关产品推荐

