Sponsored
Sponsored
This approach involves splitting the input string based on separators '.' and ':'. Use these segments to determine whether the input is a valid IPv4 or IPv6 address based on segment counts and content constraints.
Time Complexity: O(N), where N is the length of the input string.
Space Complexity: O(1), aside from the input storage.
1
2function validIPAddress(IP) {
3 const isIPv4 = (s) => /^([0-9]|[1-9][0-9]{1,2})$/.test(s) && Number(s) >= 0 && Number(s) <= 255;
4 const isIPv6 = (s) => /^[0-9a-fA-F]{1,4}$/.test(s);
5
6 if (IP.split('.').length === 4 && IP.split('.').every(isIPv4)) return 'IPv4';
7 if (IP.split(':').length === 8 && IP.split(':').every(isIPv6)) return 'IPv6';
8 return 'Neither';
9}
10
The JavaScript solution uses regular expressions to validate IPv4 and IPv6 segments, ensuring that they adhere to format and range constraints.
This approach uses regular expressions to directly match the input string against IPv4 and IPv6 patterns. It's a succinct method that can validate the format using concise expressions.
Time Complexity: O(1), since regular expression matching is handled internally and expected to be near constant-time on average.
Space Complexity: O(1), for storing pattern strings.
1
2import java.util.regex.Pattern;
In Java, we can use `Pattern.matches` to compare the IP string against regular expressions representing valid IPv4 and IPv6 formats to determine validity.