코딩테스트
[leetcode] 13. Roman to Integer
nayoon
2024. 7. 19. 19:59
1. 굳이 어렵게 가는 방법
스택 써서 이전 값 저장 후 현재값보다 이전 값이 작으면 '현재값 - 이전값' 처리 후 다시 스택에 넣기
class Solution {
public int romanToInt(String s) {
String[] sp = s.split("");
Map<String, Integer> map = new HashMap<>();
map.put("I", 1);
map.put("V", 5);
map.put("X", 10);
map.put("L", 50);
map.put("C", 100);
map.put("D", 500);
map.put("M", 1000);
Stack<Integer> stack = new Stack<>();
for(String a: sp) {
int match = map.get(a);
if (!stack.empty() && stack.peek() < match) {
int prev = stack.pop();
match -= prev;
}
stack.push(match);
}
int result = 0;
while(!stack.empty()) {
result += stack.pop();
}
return result;
}
}
2. 쉽게 가는 방법
다음 값보다 현재값이 작으면 현재값을 합에서 빼준다
class Solution {
public int romanToInt(String s) {
String[] sp = s.split("");
Map<String, Integer> map = new HashMap<>();
map.put("I", 1);
map.put("V", 5);
map.put("X", 10);
map.put("L", 50);
map.put("C", 100);
map.put("D", 500);
map.put("M", 1000);
int result = 0;
for(int i = 0; i < sp.length - 1; i++) {
if (map.get(sp[i]) >= map.get(sp[i + 1])) {
result += map.get(sp[i]);
} else {
result -= map.get(sp[i]);
}
}
result += map.get(sp[sp.length - 1]);
return result;
}
}