코딩테스트 풀이/JAVA
[LeetCode/Easy] 1108. Defanging an IP Address
무지맘
2022. 12. 20. 16:31
1. Input
1) 유효한 ip주소를 담은 문자열 배열 address
2. Output
1) “.”을 “[.]”로 치환한 결과
3. Constraint
1) address에는 IPv4 형식의 유효한 주소가 담겨있다.
4. Example
Input: address = "255.100.50.0" -> Output: "255[.]100[.]50[.]0"
5. Code
1) 첫 코드(2022/06/02)
String[] add = address.split("\\.");
String result = "";
for(int i=0 ; i<add.length-1 ; i++)
result += add[i] + "[.]";
try{
return result + add[add.length-1];
} catch(ArrayIndexOutOfBoundsException ae){
return "wrong IP address";
}
2) 한 줄로 바꿔본 코드(2022/12/20)
return address.replaceAll("\\.","[\\.]");
- 1번보다 약간 빠르고, 공간은 더 쓴다.