不会飞的章鱼

熟能生巧,勤能补拙;念念不忘,必有回响。

LeetCode-13-roman-to-integer | 罗马数字转整数

题目

LeetCode
力扣

题解

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//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
}

执行结果:

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.
------ 本文结束------
如果本篇文章对你有帮助,可以给作者加个鸡腿~(*^__^*),感谢鼓励与支持!