문제 설명 :
- 로마숫자가 문자열로 주어지고 이를 아라비아 숫자로 변환하는 문제
- 로마숫자의 예외케이스가 존재해서 예외처리만 해주면 되는 문제이다.
import java.util.*;
class Solution {
public int romanToInt(String s) {
//IV = 4, IX = 9
//XL = 40, XC = 90
//CD = 400, CM = 900
HashMap<String, Integer> map = new HashMap<String, Integer>();
int result = 0;
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);
for(int i=0; i<s.length(); i++){
if(i != s.length()-1 && this.checkIXC(s.charAt(i)+"")){
switch(s.charAt(i)+""+s.charAt(i+1)){
case "IV":
result += 4;
i++;
break;
case "IX":
result += 9;
i++;
break;
case "XL":
result += 40;
i++;
break;
case "XC":
result += 90;
i++;
break;
case "CD":
result += 400;
i++;
break;
case "CM":
result += 900;
i++;
break;
default:
result += map.get(s.charAt(i)+"");
break;
}
}else{
result += map.get(s.charAt(i)+"");
}
}
return result;
}
private boolean checkIXC(String s){
boolean result = false;
if(s.equals("I") || s.equals("X") || s.equals("C")){
result = true;
}
return result;
}
}
해설 :
- I,X,C의 경우 바로 map에 해당하는 값을 더해주는게 아니라, 예외케이스인지 확인해주는 작업을 수행했다.
- 케이스가 정해져있어서 Switch로 해결했는데, 메서드에서 바로 처리할수도 있었을 것 같고, 동일하게 map으로도 처리가 가능할 것 같다.
'Algorithm > LeetCode' 카테고리의 다른 글
[Java] 21. Merge Two Sorted Lists (0) | 2023.06.07 |
---|---|
[Java] 20. Valid Parentheses (0) | 2023.06.07 |
[Java] 14. Longest Common Prefix (0) | 2023.06.07 |
[Java] 9. Palindrome Number (0) | 2023.06.07 |
[Java] 1. Two Sum (0) | 2023.06.07 |