728x90
단순 문자열 파싱 문제이다. 무지성으로 그냥 if -else 때려 넣고 시도했다가 시간초과.... 너무 쉽게 생각한거 같다.
생각해낸 아이디어는 for문을 돌때마다 해당 symbol의 value를 넣고 그 symbol의 바로 앞 symbol이 I,X,C일 경우 x2를 해여 빼준다. 이렇게 해결한다면 O(n) 만에 값을 구할 수 있다.
class Solution {
public:
int getValue(char symbol){
int value=0;
switch (symbol){
case 'I':
value =1;
break;
case 'V':
value =5;
break;
case 'X':
value =10;
break;
case 'L':
value =50;
break;
case 'C':
value =100;
break;
case 'D':
value =500;
break;
case 'M':
value =1000;
break;
}
return value;
}
bool isCharBefore(char before, char current){
if(before == 'I'&& (current == 'V'|| current =='X')) return true;
if(before == 'X'&& (current == 'L'|| current =='C')) return true;
if(before == 'C'&& (current == 'D'|| current =='M')) return true;
return false;
}
int romanToInt(string s) {
int sum =getValue(s[0]);
int index=0;
for(int i=1;i<s.length();i++){
sum+=getValue(s[i]);
if(isCharBefore(s[i-1],s[i])){
sum -= getValue(s[i-1])*2;
}
}
return sum;
}
};
Roman to Integer - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
반응형