题目

LeetCode
力扣

题解

先维护一个map,用于建立罗马数字和整数的关系,接着挨个破译即可。

//Go
func romanToInt(s string) int {
    var charToIntMap = make(map[byte]int, 8)
    charToIntMap['I'] = 1
    charToIntMap['V'] = 5
    charToIntMap['X'] = 10
    charToIntMap['L'] = 50
    charToIntMap['C'] = 100
    charToIntMap['D'] = 500
    charToIntMap['M'] = 1000
    sum := 0
    for i:= 0; i < len(s); i++ {
        switch s[i] {
            case 'I':
            if i + 1 < len(s) && (s[i+1] == 'V' || s[i+1] == 'X') {
                sum -= charToIntMap[s[i]]
            } else {
                sum += charToIntMap[s[i]]
            }
            break

            case 'X':
            if i + 1 < len(s) && (s[i+1] == 'L' || s[i+1] == 'C') {
                sum -= charToIntMap[s[i]]
            } else {
                sum += charToIntMap[s[i]]
            }
            break

            case 'C':
            if i + 1 < len(s) && (s[i+1] == 'D' || s[i+1] == 'M') {
                sum -= charToIntMap[s[i]]
            } else {
                sum += charToIntMap[s[i]]
            }
            break

            default:
            sum += charToIntMap[s[i]]
        }
    }

    return sum
}

执行结果:

leetcode-cn执行:
执行用时:16 ms, 在所有 Go 提交中击败了22.55%的用户
内存消耗:3.1 MB, 在所有 Go 提交中击败了78.12%的用户

leetcode执行:
Runtime: 8 ms, faster than 64.36% of Go online submissions for Roman to Integer.
Memory Usage: 3.1 MB, less than 100.00% of Go online submissions for Roman to Integer.

github博客地址

相关文章:

  • 2022-01-28
  • 2022-01-12
  • 2022-12-23
  • 2021-09-21
  • 2021-11-23
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-18
  • 2021-09-21
  • 2022-01-01
  • 2021-09-25
  • 2022-01-19
  • 2021-05-26
  • 2021-07-08
相关资源
相似解决方案