13. Roman to Integer
Last updated
Last updated
time: O(n)
space: O(1)
class Solution {
public int romanToInt(String s) {
int result = 0;
for (int i = 0; i < s.length()-1;i++) {
int pre = helper(s.charAt(i));
int post = helper(s.charAt(i+1));
if (pre < post) {
result -= pre;
} else {
result += pre;
}
}
result += helper(s.charAt(s.length() - 1));
return result;
}
private int helper(char c) {
switch(c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
}
return -1;
}
/*
private int helper(char c) {
Map<Character, Integer> map = Map.of(
'I', 1, 'V', 5, 'X', 10,
'L', 50, 'C', 100, 'D', 500, 'M', 1000
);
return map.get(c);
}
*/
}