class Solution { public: int romanToInt(string s) { std::unordered_map<char, int> hm; hm['M'] = 1000; hm['D'] = 500; hm['C'] = 100; hm['L'] = 50; hm['X'] = 10; hm['V'] = 5; hm['I'] = 1; int i = 0, len = s.length(), ret = 0; while(i < len) { char c = s[i]; if(i < len - 1 && hm[s[i + 1]] > hm[s[i]]) { ret += hm[s[i + 1]] - hm[s[i]]; i ++; } else { ret += hm[s[i]]; } i ++; } return ret; } };
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)