13. Roman to Integer

https://leetcode.com/problems/roman-to-integer/description/

解题思路:

  1. 用 hashmap把那几个装入
  2. 从后到前遍历,如果当前值小于后一个则相减,反之则相加。

代码:
class Solution {
public int romanToInt(String s) {

    if(s == null || s.length() == 0) return 0;
    Map map = new HashMap();
    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;
}

}

你可能感兴趣的:(13. Roman to Integer)