【问题标题】:Panic Runtime Error index out of range [3] with length 3紧急运行时错误索引超出范围 [3],长度为 3
【发布时间】:2025-11-30 05:35:01
【问题描述】:

面临错误 Panic Runtime Error index out of range [3] with length 3。以下错误似乎表明索引超出范围或长度

panic: runtime error: index out of range [3] with length 3
main.romanToInt(0xc000022080, 0x3, 0x8)
solution.go, line 15
main.__helper__(...)
solution.go, line 30
main.main()
solution.go, line 58
func romanToInt(s string) int {
    romanNum := map[byte]int{
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }

    var sum int = 0
    for i := 0; i <= len(s); i++ {
        currentInt := romanNum[s[i]]
        nextInt := romanNum[s[i+1]]
        if currentInt < nextInt {
            sum = sum + (nextInt - currentInt)
            i += 1
        } else {
            sum = sum + currentInt
        }
    }
    return sum
}

错误指向

nextInt := romanNum[s[i+1]]

【问题讨论】:

    标签: arrays loops dictionary go slice


    【解决方案1】:

    假设您将字符串XII 传递给您的函数。这使得len(s)3,这意味着你的循环体将(如果没有发生恐慌)执行4次(当i01 , 23 因为你的条件是i &lt;= len(s)

    i2 的迭代中(即它指的是XII 中的第二个I,最后一个字符),当行

    nextInt := romanNum[s[i+1]]
    

    尝试访问下一个字符(i+1 将是 3)然后它将超出范围。请记住,切片/数组是 0 索引的。这就是恐慌的原因。

    如果在i2 时没有发生恐慌,那么它肯定会在i3 的下一次迭代中发生,因为3 超出了s,在下面一行:

    currentInt := romanNum[s[i]]
    

    要解决此问题,您需要重新考虑如何处理循环条件。在此处使用&lt;= 可能会给您带来问题。此外,在循环体中,您需要考虑到,当您查看字符串中的最后一个字符时, 没有 下一个字符,但您的代码只是假设有。解决这两个问题应该可以帮助您克服这个问题。

    【讨论】:

      【解决方案2】:

      对于 i=len(s)-1,表达式 s[i+1] 访问索引 s[len(s)],这是无效的。您正在访问的索引不存在。即使你修复它,你的循环范围也包括 len(s),所以下一次 s[i] 将超出范围。

      【讨论】: