rustgym/leetcode/
_468_validate_ip_address.rs

1struct Solution;
2
3use std::net::Ipv4Addr;
4use std::net::Ipv6Addr;
5
6impl Solution {
7    fn valid_ip_address(ip: String) -> String {
8        if Self::is_ipv4(&ip) {
9            return "IPv4".to_string();
10        }
11        if Self::is_ipv6(&ip) {
12            return "IPv6".to_string();
13        }
14        "Neither".to_string()
15    }
16
17    fn is_ipv4(ip: &str) -> bool {
18        if let Ok(v4) = ip.parse::<Ipv4Addr>() {
19            v4.to_string() == ip
20        } else {
21            false
22        }
23    }
24
25    fn is_ipv6(ip: &str) -> bool {
26        if ip.split(':').any(|p| p.is_empty()) {
27            return false;
28        }
29        ip.parse::<Ipv6Addr>().is_ok()
30    }
31}
32
33#[test]
34fn test() {
35    let ip = "172.16.254.1".to_string();
36    let res = "IPv4".to_string();
37    assert_eq!(Solution::valid_ip_address(ip), res);
38    let ip = "2001:0db8:85a3:0:0:8A2E:0370:7334".to_string();
39    let res = "IPv6".to_string();
40    assert_eq!(Solution::valid_ip_address(ip), res);
41    let ip = "256.256.256.256".to_string();
42    let res = "Neither".to_string();
43    assert_eq!(Solution::valid_ip_address(ip), res);
44    let ip = "01.01.01.01".to_string();
45    let res = "Neither".to_string();
46    assert_eq!(Solution::valid_ip_address(ip), res);
47    let ip = "2001:db8:85a3:0::8a2E:0370:7334".to_string();
48    let res = "Neither".to_string();
49    assert_eq!(Solution::valid_ip_address(ip), res);
50}