13. 罗马数字转整数 - LeetCode

13. 罗马数字转整数

贪心

class Solution {

    int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    public int romanToInt(String s) {
        int n = s.length();
        int i = 0, ans = 0;
        for(int j = 0; j < symbols.length; j++){
            if(i >= n) break;
            int m = symbols[j].length();
            while(i + m <= n){
                if(s.substring(i, i+m).equals(symbols[j])){
                    ans += values[j];
                    i += m;
                } else break;
            }
        }
        return ans;
    }
}
  • 与整数转罗马数字相同,先匹配大数,再匹配小数。
上一篇:WinDbg配置pdb路径


下一篇:dlopen配置RTLD_DEEPBIND