LeetCode 13. Roman to Integer

题目链接:
https://leetcode.com/problems/roman-to-integer/

思路:
用HashMap类,用字符型作为key,其对应的数为value。当一个字符代表的数小于其后一个字符代表的数时,这个数等于后一个字符代表的数减去该字符代表的数,否则等于二者相加。用HashMap是因为不需要思考如何遍历,直接找到Key就行。

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int romanToInt(String s) {
int ans = 0;
Map < Character, Integer > map = new HashMap < > ();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int i = 0;
while(i < s.length()) {
if((i + 1 < s.length()) && map.get(s.charAt(i + 1)) > map.get(s.charAt(i))) {
ans += map.get(s.charAt(i + 1)) - (int) map.get(s.charAt(i));
i += 2;
} else {
ans += map.get(s.charAt(i));
i++;
}
}
return ans;
}
}