반응형
코딩테스트 연습 - Valid Ip Addresses
설명
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address must be in the form of A.B.C.D, where A,B,C and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0.
Example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]. (Make sure the returned strings are sorted in order)
제한사항
- Make sure the returned strings are sorted in order
소스코드
public class Solution {
public boolean isIP(String ip) {
if (ip.startsWith("0")) {
if (ip.length() > 1) {
return false;
} else {
return (ip.length() <= 3 && Integer.parseInt(ip) <= 255);
}
} else {
return (ip.length() <= 3 && Integer.parseInt(ip) <= 255);
}
}
public ArrayList<String> restoreIpAddresses(String A) {
ArrayList<String> answer = new ArrayList<>();
for (int i = 1; i < A.length(); i++) {
StringBuilder sb = new StringBuilder(A);
sb.insert(i, ".");
String[] splited = sb.toString().split("\\.");
if (!isIP(splited[0]) || splited[1].length() > 9) continue;
else {
for (int j = 1; j < splited[1].length(); j++) {
StringBuilder sb2 = new StringBuilder(splited[1]);
sb2.insert(j, ".");
String[] splited2 = sb2.toString().split("\\.");
if (!isIP(splited2[0]) || splited2[1].length() > 6) continue;
else {
for (int k = 1; k < splited2[1].length(); k++) {
StringBuilder sb3 = new StringBuilder(splited2[1]);
sb3.insert(k, ".");
String[] splited3 = sb3.toString().split("\\.");
if (!isIP(splited3[0]) || !isIP(splited3[1])) continue;
else {
// System.out.println(Integer.parseInt(splited[0]) + "." + Integer.parseInt(splited2[0])
// + "." + Integer.parseInt(splited3[0]) + "." + Integer.parseInt(splited3[1]));
answer.add(Integer.parseInt(splited[0]) + "." + Integer.parseInt(splited2[0])
+ "." + Integer.parseInt(splited3[0]) + "." + Integer.parseInt(splited3[1]));
}
}
}
}
}
}
return answer;
}
}
반응형