leetcode-13-java

问题:13.Roman to Integer

1
2
3
4
5
6
7
8
9
10
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4

leetcode地址

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
45
46
47
48
49
50
51
class Solution {
private static Map<String, Integer> doubleMap = new HashMap<String, Integer>() {{
put("CM", 900);
put("CD", 400);
put("XC", 90);
put("XL", 40);
put("IX", 9);
put("IV", 4);
}};


private static Map<String, Integer> singleMap = new HashMap<String, Integer>() {{
put("M", 1000);
put("D", 500);
put("C", 100);
put("L", 50);
put("X", 10);
put("V", 5);
put("I", 1);
}};


public static int romanToInt(String s) {
if (null == s || s.length() == 0) {
return 0;
}

int sum = 0;
int index = 0;
while (index < s.length()) {
int end = index + 2;
if (end <= s.length()) {
String douStr = s.substring(index, end);
if (null != doubleMap.get(douStr)) {
sum += doubleMap.get(douStr);
index += 2;
continue;
}
}

end = index + 1;
String douStr = s.substring(index, end);
if (null != singleMap.get(douStr)) {
sum += singleMap.get(douStr);
index += 1;
continue;
}
}
return sum;
}
}