13. 罗马数字转整数
链接:https://leetcode-cn.com/problems/roman-to-integer/
题目描述见链接内容。
解法1:动态替换
我的做法太表面了,既然有6种情况是特殊的,我将这六种特殊的情况也都添加到配置中,然后首先去判断六种情况开头的字符,如果是的话,按照这六种情况进行计算,并且i += 2
var romanToInt = function (s) {
const map = new Map([
['I', 1],
['V', 5],
['X', 10],
['L', 50],
['C', 100],
['D', 500],
['M', 1000],
['IV', 4],
['IX', 9],
['XL', 40],
['XC', 90],
['CD', 400],
['CM', 900]
]);
const length = s.length;
let result = 0;
for (let i = 0; i < length; i++) {
let current = s[i];
let currentResult = map.get(current);
if (current === 'I' || current === 'X' || current === 'C') {
if (s[i + 1]) {
let newCurrent = current + s[i + 1];
const temp = map.get(newCurrent);
if (temp) {
result += temp;
i++;
} else {
result += currentResult;
}
} else {
result += currentResult;
}
} else {
result += currentResult;
}
}
return result;
};
执行结果:执行用时192 ms,超过了23%的JavaScript提交,内存消耗: 46.7 MB,超过了7%的JavaScript提交
解法2:看穿本质
看了其他人的解法,发现自己还是太笨,实际上这六种特殊情况的统一特点就是,如果小值在大值的左边,小值做减法,大值做加法,如果小值在大值的右边,小值做减法,大值做加法
要注意的是,六种特殊情况肯定是符合这个规律的,但是这个规律可能涵盖更多的情况,但是除了这六种之外的情况,并不是罗马数字正确的表达方式,所以可以不考虑
var romanToInt = function (s) {
const map = new Map([
['I', 1],
['V', 5],
['X', 10],
['L', 50],
['C', 100],
['D', 500],
['M', 1000]
]);
const length = s.length;
let result = 0;
for (let i = 0; i < length; i++) {
const current = s[i],
next = s[i + 1];
const currentVal = map.get(current),
nextVal = map.get(next);
result = next && nextVal > currentVal ? result - currentVal : result + currentVal;
}
return result;
};
执行用时:172ms, 在所有JavaScript提交中击败了54.91%
的用户,内存消耗:43.6MB,在所有JavaScript提交中击败了60.67%的用户