문제
문제 링크 : Roman to Integer
풀이
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
let romanObj = new Map();
romanObj.set("I", 1).set("V", 5).set("X", 10).set("L", 50).set("C", 100).set("D", 500).set("M", 1000)
let sum = 0
for(let i=0; i<s.length; i++) {
if((s[i] === "I" && s[i+1] === "V") || (s[i] === "I" && s[i+1] === "X")) {
sum += romanObj.get(s[i+1]) - romanObj.get(s[i])
i++
continue
}
if((s[i] === "X" && s[i+1] === "L") || (s[i] === "X" && s[i+1] === "C")) {
sum += romanObj.get(s[i+1]) - romanObj.get(s[i])
i++
continue
}
if((s[i] === "C" && s[i+1] === "D") || (s[i] === "C" && s[i+1] === "M")) {
sum += romanObj.get(s[i+1]) - romanObj.get(s[i])
i++
continue
}
sum += romanObj.get(s[i])
}
return sum
};
- Map을 만들어 각 로마 숫자에 맞는 숫자를 set
- for문을 돌며 예외 사항만 체크하여 진행(4,9,40,90,400,900)
- sum을 return
- Runtime 122 ms, Memory 52.1 MB
다른 풀이 1
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
let map = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
let result = 0;
for(let i=0; i<s.length; i++) {
let curr = map[s[i]]
let next = map[s[i+1]]
if(curr < next) {
result += next-curr
i++
} else {
result += curr
}
}
return result
};
- 같은 방식이지만 if문을 많이 걸러냄
- 어차피 로마 숫자는 큰 문자부터 나오고 예외사항은 next가 curr 보다 큰 경우
- Runtime 110 ms, Memory 47 MB
let으로 선언한 map, curr, next를 const로 선언하면 Runtime과 Memory 효율 상승
=> Runtime 91 ms, Memory 46.9 MB
'알고리즘 풀이 > leetcode' 카테고리의 다른 글
[leetcode, JS] 20. Valid Parentheses (0) | 2023.09.22 |
---|---|
[leetcode, JS] 14. Longest Common Prefix (0) | 2023.09.21 |
[leetcode, JS] 9. Palindrome Number (0) | 2023.09.21 |
[leetcode, JS] 2. Add Two Numbers (0) | 2023.09.20 |
[leetcode, JS] 1. Two Sum (0) | 2023.09.20 |