LeetCode#13 - 罗马数字转整数
题目描述
代码实现
// 根据提示,倒序处理字符串比较简单
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 result = m[s[s.length() - 1]];
for (int i = s.length() - 2; i >= 0; i--)
{
if (m[s[i]] >= m[s[i + 1]])
result += m[s[i]];
else
result -= m[s[i]];
}
return result;
}
};
// 测试一下正序处理会不会改善程序性能
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 result = 0;
for (int i = 0; i < s.length() - 1; i++)
{
if (m[s[i]] >= m[s[i + 1]])
result += m[s[i]];
else
result -= m[s[i]];
}
result += m[s[s.length() - 1]];
return result;
}
};
// LeetCode 题解内阅读量较高的一个算法,经测试,性能较差,而且可读性差,我认为并不可取
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}};
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];
}
return r;
}
};
题目链接:罗马数字转整数