leetcode-13-字符串题-罗马数字转整数 发表于 2020-03-13 | 分类于 数据结构与算法 题目 解法12345678910111213141516171819202122class Solution {public: int romanToInt(string s) { if(s.empty()) return 0; unordered_map<char, int> hasher{{'I', 1},{'V', 5},{'X', 10},{'L', 50},{'C', 100},{'D', 500},{'M', 1000}}; int res = 0; for(int i = 0; i < s.size(); ++i){ bool condition = (i+1 < s.size()) && (s[i] == 'I' && (s[i+1] == 'V' || s[i+1] == 'X')) || (s[i] == 'X' && (s[i+1] == 'L' || s[i+1] == 'C')) || (s[i] == 'C' && (s[i+1] == 'D' || s[i+1] == 'M')); if(condition){ res += hasher[s[i+1]] - hasher[s[i]]; ++i; }else{ res += hasher[s[i]]; } } return res; }};