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
2using System.Text.RegularExpressions;
3
4public class Solution {
5 public string ValidIPAddress(string IP) {
string ipv4Pattern = "^((25[0-5]|(2[0-4]|1{0,1}\d{1})\d)\.){3}(25[0-5]|(2[0-4]|1{0,1}\d{1})\d)$";
string ipv6Pattern = "^(([0-9a-fA-F]{1,4}):){7}([0-9a-fA-F]{1,4})$";
if (Regex.IsMatch(IP, ipv4Pattern)) return "IPv4";
if (Regex.IsMatch(IP, ipv6Pattern)) return "IPv6";
return "Neither";
}
}
The C# solution similarly uses `Regex.IsMatch` to validate the input string using predetermined patterns that define valid IPv4 and IPv6 formats.