13. Roman to Integer

根据罗马数字的写法,连续出现2个或3个相同字母的情况一定是其左边有一个大数或者相等的数。即是 III 或者 VII
不存在 IIV这种写法,即不允许有连续减去两个小数的写法。

public class Solution {
    public int romanToInt(String s) {
        if(s.length()<1)
            return 0;
            
        int size=s.length();
        int res=0;
        
        
        Map<Character,Integer> mp=new HashMap<Character,Integer>();
        // 哈希表的正确用法
        
        mp.put('I',1);
        mp.put('V',5);
        mp.put('X',10);
        mp.put('L',50);
        mp.put('C',100);
        mp.put('D',500);
        mp.put('M',1000);
        
        //根据罗马数字的写法,连续出现2个或3个相同字母的情况一定是其左边有一个大数或者相等的数。即是 III 或者 VII
        //不存在  IIV这种写法,即不允许有连续减去两个小数的写法。
        //
        
        res=mp.get(s.charAt(size-1));
        
        for(int i=size-2;i>=0;i--)
        {
            int t=mp.get(s.charAt(i));
            int t_r=mp.get(s.charAt(i+1));
            if(t>=t_r)
                res+=t;
            else
                res-=t;
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/aguai1992/p/5346563.html