[Link] https://leetcode.com/problems/roman-to-integer/
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
import java.util.HashMap;
class Solution {
public HashMap<Character, Integer> hm = new HashMap<>();
public int romanToInt(String s) {
int l = s.length(), sum = 0;
String str;
for(int i = l - 1; i >= 0; i--) {
char c = s.charAt(i);
if(hm.get(c) == null) {
hm.put(c, i);
}
}
for(int i = 0; i < l ; i++) {
char c = s.charAt(i);
if(c == 'I') sum += mul('V','X', i) * getNum(c);
else if(c == 'X') sum += mul('L','C', i) * getNum(c);
else if(c == 'C') sum += mul('D','M', i) * getNum(c);
else sum += getNum(c);
}
return sum;
}
int mul(char x, char y, int i) {
int max = Integer.MIN_VALUE;
if(hm.containsKey(x)) max = hm.get(x);
if(hm.containsKey(y)) max = Math.max(max, hm.get(y));
return max < i ? 1 : -1;
}
boolean startWithOne(char c) { return (c == 'I' || c == 'X' || c == 'C') ? true : false; }
int getNum(char c) {
if(c == 'I') return 1;
else if(c == 'V') return 5;
else if(c == 'X') return 10;
else if(c == 'L') return 50;
else if(c == 'C') return 100;
else if(c == 'D') return 500;
else return 1000;
}
}