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
2def validIPAddress(IP: str) -> str:
3 def isIPv4(s):
4 try: return str(int(s)) == s and 0 <= int(s) <= 255
5 except: return False
6
7 def isIPv6(s):
8 try: return len(s) <= 4 and int(s, 16) >= 0
9 except: return False
10
11 if IP.count('.') == 3 and all(isIPv4(i) for i in IP.split('.')):
12 return 'IPv4'
13 if IP.count(':') == 7 and all(isIPv6(i) for i in IP.split(':')):
14 return 'IPv6'
15 return 'Neither'
16
The Python solution splits the input string by '.' for IPv4 validation and checks each part for integer validation within [0, 255] without leading zeros. Similarly, it splits by ':' for IPv6 and checks the hexadecimal validity of each segment.
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.