-
1일 (13. Roman to Integer)지식/알고리즘 2023. 9. 21. 17:01
public static void main(String[] args) { // K:V 형태니까 맵으로 접근 Map<String, Integer> map = new HashMap<>(); int temp = 0; int preValue = 0; boolean isIXC = false; // 특수한 3가지 경우일 때 알려주기 위함 (I다음 V or X, X 다음 L or C, C 다음 D or M 일 경우) 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); String problem = "MCMXCIV"; // 1994 Stack<Integer> stack = new Stack<>(); for(int i = 0; i < problem.length(); i++) { String s = String.valueOf(problem.charAt(i)); if(isIXC) { // 3가지 경우일때 switch (preValue) { case 1: if(map.get(s) == 5 || map.get(s) == 10) { temp += (map.get(s) - 2); } else { temp += map.get(s); } break; case 10: if(map.get(s) == 50 || map.get(s) == 100) { temp += (map.get(s) - 20); } else { temp += map.get(s); } break; case 100: if(map.get(s) == 500 || map.get(s) == 1000) { temp += (map.get(s) - 200); } else { temp += map.get(s); } break; } isIXC = false; } else { temp += map.get(s); } if(s.equals("I") || s.equals("X") || s.equals("C")) { // 3가지 경우 boolean on isIXC = true; preValue = map.get(s); } } System.out.println(temp); // 1994 }
리트코드 쉬움 난이도인데 오랜만이라 어렵다..
평균실행시간보다 더 길고, 메모리는 더욱 잡아먹는 코드로 통과했다.
비슷한 문제를 또 다시 마주하게 된다면 Stack을 사용해서 깔끔하게 코드를 관리하는게 나을 것 같다.
https://leetcode.com/problems/roman-to-integer
LeetCode - The World's Leading Online Programming Learning Platform
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
'지식 > 알고리즘' 카테고리의 다른 글
페이징과 주소 변환 (0) 2023.09.26 5일 (20. Valid Parentheses) (0) 2023.09.25 4일 (14. Longest Common Prefix) (0) 2023.09.24 3일 (1048. Longest String Chain) (0) 2023.09.23 2일 (더 맵게) (0) 2023.09.22