An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
Given a string, find out if it satisfies the IPv4 address naming rules.
Example
For inputString = "172.16.254.1", the output should be
solution(inputString) = true;
For inputString = "172.316.254.1", the output should be
solution(inputString) = false.
316 is not in range [0, 255].
For inputString = ".254.255.0", the output should be
solution(inputString) = false.
There is no first number.
Input/Output
[execution time limit] 3 seconds (java)
[memory limit] 1 GB
[input] string inputString
A string consisting of digits, full stops and lowercase English letters.
Guaranteed constraints:
1 ≤ inputString.length ≤ 30.
[output] boolean
true if inputString satisfies the IPv4 address naming rules, false otherwise.
boolean solution(String inputString) {
// . 기준으로 split
String [] arr = inputString.split("\\\\.");
// 숫자만 허용하는 정규식
String REGEXP_PATTERN_NUMBER = "^[\\\\d]*$";
// xxx.xxx.xxx.xxx 으로 구성되어야함
if (arr.length != 4) return false;
for (String s : arr) {
// 공백은 거짓
if (s.equals("")) return false;
// 숫자 이외의 문자 존재 시 거짓
if (!Pattern.matches(REGEXP_PATTERN_NUMBER, s)) return false;
// 두 자리 이상의 숫자일 경우 앞자리에 0 이 존재하면 거짓
if (s.length() > 1 && s.charAt(0) == '0') return false;
// Integer 길이를 넘는 문자가 올 가능성 대비
long n = Long.parseLong(s);
// 0 ~ 255 만 허용
if (n < 0 || n > 255) return false;
}
return true;
}