标签:ret mission 图片 else miss man leetcode string i++
目录
解法一:从右至左,对于出现的每个字符逐个判断,累加。时间复杂度为O(n)
class Solution {
public:
int romanToInt(string s) {
int i,n = s.size(),anw = 0;
for(i = n-1;i >= 0;i--)
{
if(s[i] == 'M')
{
if(s[i-1] == 'C')
{
anw += 900;
i--;
}
else
{
anw += 1000;
}
}
else if(s[i] == 'D')
{
if(s[i-1] == 'C')
{
anw += 400;
i--;
}
else
{
anw += 500;
}
}
else if(s[i] == 'C')
{
if(s[i-1] == 'X')
{
anw += 90;
i--;
}
else
{
anw += 100;
}
}
else if(s[i] == 'L')
{
if(s[i-1] == 'X')
{
anw += 40;
i--;
}
else
{
anw += 50;
}
}
else if(s[i] == 'X')
{
if(s[i-1] == 'I')
{
anw += 9;
i--;
}
else
{
anw += 10;
}
}
else if(s[i] == 'V')
{
if(s[i-1] == 'I')
{
anw += 4;
i--;
}
else
{
anw += 5;
}
}
else if(s[i] == 'I')
{
anw += 1;
}
//printf("%d\n",anw);
}
return anw;
}
};
解法二:从左至右。如果之前的数字小于当前的就减去之前的数字,否则就加上。最后一个字符无论如何都加上。时间复杂度O(n)
class Solution {
public:
int romanToInt(string s) {
map<char,int> m;
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
int i,n = s.size(),anw = 0;
int before = m[s[0]],now = 0;
for(i = 1;i < n;i++)
{
now = m[s[i]];
if(before < now)
{
anw -= before;
}
else
{
anw += before;
}
before = now;
}
anw += before;
return anw;
}
};
标签:ret mission 图片 else miss man leetcode string i++
原文地址:https://www.cnblogs.com/multhree/p/10320230.html