LeetCode/solutions/13. Roman to Integer.md

28 lines
1.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/description/)
# 思路
罗马数字转阿拉伯数字。七个大写字母对应七个数对应关系可以用一个数组或者map来实现。
用res代表结果将代表罗马数字的字符串s从前往后遍历如果当前字母对应的数大于等于下一个字母对应的数则res加上对应的数否则减。
注意根据题意是没有可能发生s[i] < s[i + 1] < s[i + 2]
# C++
```
class Solution {
public:
int romanToInt(string s) {
vector<int>mp(26);
mp['I' - 'A'] = 1;
mp['V' - 'A'] = 5;
mp['X' - 'A'] = 10;
mp['L' - 'A'] = 50;
mp['C' - 'A'] = 100;
mp['D' - 'A'] = 500;
mp['M' - 'A'] = 1000;
int res = mp[s[s.size() - 1] - 'A'];
for(int i = 0; i < s.size() - 1; i++){
if(mp[s[i] - 'A'] < mp[s[i + 1] - 'A']) res -= mp[s[i] - 'A'];
else res += mp[s[i] - 'A'];
}
return res;
}
};
```