[Leetcode] Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

------------------------

题是比较简单,但是解法中用了static block。

public class Solution {
    
    private static Map<Character, Integer> map;
    static {
        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);
    }

    public int romanToInt(String s) {
        if(s == null || s.length() == 0)
            return 0;
        int res = 0;
        for (int i = 0; i < s.length() - 1; ++i){
            int cur = map.get(s.charAt(i));
            int next = map.get(s.charAt(i + 1));
            if(cur < next) {
                res -= cur;
            } else {
                res +=cur;
            }
        }
        res += map.get(s.charAt(s.length()-1));
        return res;
    }
}

------------------------------

Static block: http://stackoverflow.com/questions/2943556/static-block-in-java

Notice: the order of execution is: static initializer, instance initializer, constructor

posted @ 2015-09-20 13:21  Phoebe815  阅读(158)  评论(0编辑  收藏  举报