zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    sql语句添加查询字段
    SqlServer Case when then用法总结
    单例与多线程
    HttpSession详解
    范式
    SQL语句中的Having子句与where子句
    HTTP无状态
    字节流与字符流的区别
    选择排序
    ReentrantLock VS synchronized
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4823272.html
Copyright © 2011-2022 走看看