美文网首页
13. Roman to Integer

13. Roman to Integer

作者: becauseyou_90cd | 来源:发表于2018-07-30 23:00 被阅读0次

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<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;
}

}

相关文章

网友评论

      本文标题:13. Roman to Integer

      本文链接:https://www.haomeiwen.com/subject/syiqvftx.html