- 从后往前遍历字符串
- 当前一个字符代表的数值比后一个小时,用最终结果减去这个数值
- 否则,用最终结果加上这个数值
Implementation
public class Solution {
public int romanToInt(String s) {
if (s == null || s.length() == 0)
return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
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 length = s.length();
int result = map.get(s.charAt(length - 1));
int current = result;
for (int i = length - 2; i >= 0; i--) {
int pre = map.get(s.charAt(i));
result += (pre < current? -pre: pre);
current = pre;
}
return result;
}
}