https://leetcode.com/problems/roman-to-integer/description/
解题思路:
- 用 hashmap把那几个装入
- 从后到前遍历,如果当前值小于后一个则相减,反之则相加。
代码:
class Solution {
public int romanToInt(String s) {
if(s == null || s.length() == 0) return 0;
Map<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 len = s.length();
int sum = map.get(s.charAt(len - 1));
for(int i = s.length() - 2; i >= 0; i--){
if(map.get(s.charAt(i)) >= map.get(s.charAt(i + 1))){
sum += map.get(s.charAt(i));
} else {
sum -= map.get(s.charAt(i));
}
}
return sum;
}
}