leetcode-13 roman-to-integer(罗马数字转整数)

先来看一下题目描述:

 

这道题需要用HashMap存取。罗马数字作为键,数字作为值,然后从右往左进行遍历判断

 public static int romanToInt(String s) {
         if(s==" "||s==null)return 0;
         Map<Character, Integer>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(),result = map.get(s.charAt(len-1));
            for(int i = len - 2 ; i>=0 ; i--){
//从倒数第二个元素和倒数第一个元素进行比较
if(map.get(s.charAt(i)) >= map.get(s.charAt(i+1))) result += map.get(s.charAt(i)); else result -= map.get(s.charAt(i));//例如IV } return
result; }

 

posted @ 2018-11-21 11:30  青衫z  阅读(123)  评论(0)    收藏  举报