个人解法
class Solution {
public:
int romanToInt(string s) {
vector<char> list={'I','V','X','L','C','D','M'};
vector<int> list1={1,5,10,50,100,500,1000};
map<char,int> kv;
for(int i=0;i<list.size();i++)
{
kv.insert(pair<char,int>(list[i],list1[i]));
}
int sum=0;
for(int i=0;i<s.size();i++)
{
if(i>=1)
{
if(s[i]=='V'&&s[i-1]=='I') {sum=sum+3; continue;}
if(s[i]=='X'&&s[i-1]=='I') {sum=sum+8; continue;}
if(s[i]=='L'&&s[i-1]=='X') {sum=sum+30;continue;}
if(s[i]=='C'&&s[i-1]=='X') {sum=sum+80;continue;}
if(s[i]=='D'&&s[i-1]=='C') {sum=sum+300;continue;}
if(s[i]=='M'&&s[i-1]=='C') {sum=sum+800;continue;}
}
sum+=kv[s[i]];
}
return sum;
}
};
用了一下map,但是map添加数据太麻烦,就写了俩vector挺占内存的
官方解法
class Solution {
public:
int romanToInt(string s) {
unordered_map<string, int> m = {{"I", 1}, {"IV", 3}, {"IX", 8}, {"V", 5}, {"X", 10}, {"XL", 30}, {"XC", 80}, {"L", 50}, {"C", 100}, {"CD", 300}, {"CM", 800}, {"D", 500}, {"M", 1000}};//IV=3是因为防止之前的数是I,减1再加4。后面都一样
int r = m[s.substr(0, 1)];
for(int i=1; i<s.size(); ++i){
string two = s.substr(i-1, 2);
string one = s.substr(i, 1);
r += m[two] ? m[two] : m[one];//m[two]如果存在则加m[two],否则加m[one]
}
return r;
}
};
作者:QQqun902025048
链接:https://leetcode-cn.com/problems/roman-to-integer/solution/2-xing-python-on-by-knifezhu/
substr是用于获取子字符串的方法substr(何处开始,多少字符)