//Go funcromanToInt(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 }
执行结果:
1 2 3 4 5 6 7
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.