mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
28 lines
1.0 KiB
Markdown
28 lines
1.0 KiB
Markdown
# [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;
|
||
}
|
||
};
|
||
```
|