Skip to content

Commit 801ec12

Browse files
committed
Roman to Integer(faster than 99.99%)
1 parent 0ea9c1b commit 801ec12

File tree

1 file changed

+16
-28
lines changed

1 file changed

+16
-28
lines changed
+16-28
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,22 @@
11
class Solution {
22
public int romanToInt(String s) {
3-
Map<String, Integer> map = new HashMap<String, Integer>(13) {
4-
{
5-
put("I", 1);
6-
put("V", 5);
7-
put("X", 10);
8-
put("L", 50);
9-
put("C", 100);
10-
put("D", 500);
11-
put("M", 1000);
12-
put("IV", 4);
13-
put("IX", 9);
14-
put("XL", 40);
15-
put("XC", 90);
16-
put("CD", 400);
17-
put("CM", 900);
18-
}
19-
};
20-
21-
int res = 0;
22-
int len = s.length();
23-
for (int i = 0; i < len; ++i) {
24-
if (i != len - 1 && map.get(s.substring(i, i + 2)) != null) {
25-
res += map.get(s.substring(i, i + 2));
26-
++i;
27-
continue;
3+
if (s == null || s.isEmpty()) {
4+
return 0;
5+
}
6+
String str = "IVXLCDM";
7+
int[] num = {1, 5, 10, 50, 100, 500, 1000};
8+
int ans = 0;
9+
int i = 0;
10+
int pre = 999, cur = 0;
11+
while (i < s.length()) {
12+
cur = str.indexOf(s.charAt(i++));
13+
if (pre < cur) {
14+
ans = ans + num[cur] - 2 * num[pre];
15+
} else {
16+
ans += num[cur];
2817
}
29-
res += map.get(s.substring(i, i + 1));
18+
pre = cur;
3019
}
31-
return res;
32-
20+
return ans;
3321
}
3422
}

0 commit comments

Comments
 (0)