LeetCode 13.罗马数字转整数
目录
0. 题目描述
1. 解题分析
(1)思路也很简单:逐一读取字符串,根据转换规则进行转换。为了减少if逻辑判断,用了map来存储罗马数字与对应的整数,增加了一点空间消耗。
#include<string>
#include<map>
static auto _=[]() //提升io性能
{
ios::sync_with_stdio(false);
cin.tie(0);
return 0;
}();
class Solution {
public:
int romanToInt(string s) {
string roman[] = { "I", "V", "X", "L", "C", "D", "M",
"IV", "IX", "XL", "XC", "CD", "CM"};
int number[] = { 1, 5, 10, 50, 100, 500, 1000,
4, 9, 40, 90, 400, 900};
map<string, int> dictionary;
for (int i = 0; i < 13; i++) {
dictionary.insert(pair<string, int>(roman[i], number[i]));
}
int intNum = 0;
int length = s.length();
for (int i = 0; i < length; i++) {
if (i != length - 1) {
string temp = s.substr(i, 2);
if (temp == "IV" || temp == "IX" ||
temp == "XL" || temp == "XC" ||
temp == "CD" || temp == "CM") {
intNum += dictionary[s.substr(i, 2)];
i++;
}
else {
intNum += dictionary[s.substr(i, 1)];
}
}
else {
intNum += dictionary[s.substr(i, 1)];
}
}
return intNum;
}
};
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。
测试用时56ms,优于81%左右的提交。而直接多层的if判断,测试用时44ms,优于96%左右的提交。
结果表明跟直接写多层的if判断比起来,反而更增加了时间空间消耗= =。可以说是费力不讨好了……唯一优点是代码简洁易读。