[LeetCode]Roman to Integer

来源:互联网 发布:linux 制作镜像 编辑:程序博客网 时间:2024/06/02 02:17
解题思路:
0,先准备一个hash table,把roman numeral对应到int的整数中
1,从最后一个字符向前遍历;记录当前字符temp 和 前一个字符tempPre
2,map temp/tempPre to int, 如果temp < tempPre, 说明这个数字是要减掉的,否则就把这个数字 + 上

上述规律是罗马数字的定义决定的 


class Solution {public:    std::unordered_map<char, int> romanMapInt;    Solution(){        romanMapInt['I'] = 1;        romanMapInt['V'] = 5;        romanMapInt['X'] = 10;        romanMapInt['L'] = 50;        romanMapInt['C'] = 100;        romanMapInt['D'] = 500;        romanMapInt['M'] = 1000;    }    int romanToInt(string s) {        if (s.length() == 0){            return 0;        }        char preChar = *s.rbegin();        string::reverse_iterator rit = s.rbegin();        int ret = 0;        while (rit != s.rend()){            int temp = romanMapInt[*rit];            int tempPre = romanMapInt[preChar];            if (temp < tempPre){                ret -= temp;            }else{                ret += temp;                preChar = *rit;            }            ++rit;        }        return ret;    }};


0 0
原创粉丝点击