13. Roman to Integer #String (Easy)

Problem:###

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

Solution:###

  • 罗马数字表达规则:右加左减,在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。在一个较大的数字的左边记上一个较小的罗马数字,表示大数字减小数字。但是,左减不能跨越等级。比如,99不可以用IC表示,用XCIX表示。

所以本题可以从s的末尾往前遍历,如果前一位数字小于后一位,则表示减,大于或者等于后一位则表示加。

class Solution {
public:
    int romanToInt(string s) {
        if (s.length() == 0) return 0;
        int result = 0;
        unordered_map table;
        table['I'] = 1;
        table['V'] = 5;
        table['X'] = 10;
        table['L'] = 50;
        table['C'] = 100;
        table['D'] = 500;
        table['M'] = 1000;
        
        result += table[s.back()];
        
        for(int i = s.length() - 2;i >= 0;i--)
        {
            if(table[s[i]] < table[s[i + 1]]) 
                result -= table[s[i]];
            else 
                result += table[s[i]];
        }
        return result;
    }
};

LeetCode Discussion
Roman Number Chart

MEMO:###

The difference between char and string.

unordered_map table; 
table['I'] = 1; //correct
table["I"] = 1; //not correct

你可能感兴趣的:(13. Roman to Integer #String (Easy))