← Static tasks

468. Validate IP Address

leetcode medium

#array#csharp#leetcode#medium#string

Task

Допустимый IPv4-адрес — это IP в форме "x1.x2.x3.x4", где 0 <= xi <= 255 и xi не может содержать ведущие нули. Например, "

192.168.1.1

" и "

192.168.1.0

" являются допустимыми IPv4-адресами, тогда как "192.168.01.1", "192.168.1.00" и "192.168@1.1" являются недопустимыми IPv4-адресами.

Допустимый IPv6-адрес — это IP в форме "x1:x2:x3:x4:x5:x6:x7

", где:

1 <= xi.length <= 4

xi — это шестнадцатеричная строка, которая может содержать цифры, строчные английские буквы ('a' до 'f') и прописные английские буквы ('A' до 'F').

Ведущие нули в xi допускаются.

Пример:

Input: queryIP = "172.16.254.1"

Output: "IPv4"

Explanation: This is a valid IPv4 address, return "IPv4".

C# solution

matched/original
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
    public string ValidateIPv4(string IP) {
        var nums = IP.Split(new char[] { '.' });
        if (nums.Length != 4) return "Neither";
        foreach (var x in nums) {
            if (x.Length == 0 || x.Length > 3) return "Neither";
            if (x[0] == '0' && x.Length != 1) return "Neither";
            if (!x.All(char.IsDigit)) return "Neither";
            if (int.Parse(x) > 255) return "Neither";
        }
        return "IPv4";
    }
    public string ValidateIPv6(string IP) {
        var nums = IP.Split(new char[] { ':' });
        var hexdigits = "0123456789abcdefABCDEF";
        if (nums.Length != 8) return "Neither";
        foreach (var x in nums) {
            if (x.Length == 0 || x.Length > 4) return "Neither";
            if (x.Any(ch => hexdigits.IndexOf(ch) == -1)) return "Neither";
        }
        return "IPv6";
    }
    public string ValidIPAddress(string IP) {
        if (IP.Count(ch => ch == '.') == 3) {
            return ValidateIPv4(IP);
        } else if (IP.Count(ch => ch == ':') == 7) {
            return ValidateIPv6(IP);
        } else {
            return "Neither";
        }
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public string ValidateIPv4(string IP) {
        var nums = IP.Split(new char[] { '.' });
        if (nums.size() != 4) return "Neither";
        foreach (var x in nums) {
            if (x.size() == 0 || x.size() > 3) return "Neither";
            if (x[0] == '0' && x.size() != 1) return "Neither";
            if (!x.All(char.IsDigit)) return "Neither";
            if (int.Parse(x) > 255) return "Neither";
        }
        return "IPv4";
    }
    public string ValidateIPv6(string IP) {
        var nums = IP.Split(new char[] { ':' });
        var hexdigits = "0123456789abcdefABCDEF";
        if (nums.size() != 8) return "Neither";
        foreach (var x in nums) {
            if (x.size() == 0 || x.size() > 4) return "Neither";
            if (x.Any(ch => hexdigits.IndexOf(ch) == -1)) return "Neither";
        }
        return "IPv6";
    }
    public string ValidIPAddress(string IP) {
        if (IP.size()(ch => ch == '.') == 3) {
            return ValidateIPv4(IP);
        } else if (IP.size()(ch => ch == ':') == 7) {
            return ValidateIPv6(IP);
        } else {
            return "Neither";
        }
    }
}

Java solution

matched/original
class Solution {
    public String validateIPv4(String IP) {
        String[] nums = IP.split("\\.", -1);
        for (String x : nums) {
            if (x.length() == 0 || x.length() > 3) return "Neither";
            if (x.charAt(0) == '0' && x.length() != 1) return "Neither";
            for (char ch : x.toCharArray()) {
                if (!Character.isDigit(ch)) return "Neither";
            }
            if (Integer.parseInt(x) > 255) return "Neither";
        }
        return "IPv4";
    }

    public String validateIPv6(String IP) {
        String[] nums = IP.split(":", -1);
        String hexdigits = "0123456789abcdefABCDEF";
        for (String x : nums) {
            if (x.length() == 0 || x.length() > 4) return "Neither";
            for (char ch : x.toCharArray()) {
                if (hexdigits.indexOf(ch) == -1) return "Neither";
            }
        }
        return "IPv6";
    }

    public String validIPAddress(String IP) {
        if (IP.chars().filter(ch -> ch == '.').count() == 3) {
            return validateIPv4(IP);
        } else if (IP.chars().filter(ch -> ch == ':').count() == 7) {
            return validateIPv6(IP);
        } else {
            return "Neither";
        }
    }
}

JavaScript solution

matched/original
class Solution {
    validateIPv4(IP) {
        const nums = IP.split(".");
        if (nums.length !== 4) return "Neither";
        for (let x of nums) {
            if (x.length === 0 || x.length > 3) return "Neither";
            if (x[0] === '0' && x.length !== 1) return "Neither";
            if (!/^\d+$/.test(x)) return "Neither";
            if (parseInt(x) > 255) return "Neither";
        }
        return "IPv4";
    }

    validateIPv6(IP) {
        const nums = IP.split(":");
        const hexdigits = "0123456789abcdefABCDEF";
        if (nums.length !== 8) return "Neither";
        for (let x of nums) {
            if (x.length === 0 || x.length > 4) return "Neither";
            for (let ch of x) {
                if (!hexdigits.includes(ch)) return "Neither";
            }
        }
        return "IPv6";
    }

    validIPAddress(IP) {
        if (IP.split(".").length === 4) {
            return this.validateIPv4(IP);
        } else if (IP.split(":").length === 8) {
            return this.validateIPv6(IP);
        } else {
            return "Neither";
        }
    }
}

Python solution

matched/original
class Solution:
    def validateIPv4(self, IP: str) -> str:
        nums = IP.split(".")
        for x in nums:
            if len(x) == 0 or len(x) > 3:
                return "Neither"
            if x[0] == '0' and len(x) != 1:
                return "Neither"
            if not x.isdigit():
                return "Neither"
            if int(x) > 255:
                return "Neither"
        return "IPv4"

    def validateIPv6(self, IP: str) -> str:
        nums = IP.split(":")
        hexdigits = "0123456789abcdefABCDEF"
        for x in nums:
            if len(x) == 0 or len(x) > 4:
                return "Neither"
            for ch in x:
                if ch not in hexdigits:
                    return "Neither"
        return "IPv6"

    def validIPAddress(self, IP: str) -> str:
        if IP.count(".") == 3:
            return self.validateIPv4(IP)
        elif IP.count(":") == 7:
            return self.validateIPv6(IP)
        else:
            return "Neither"

Go solution

matched/original
package main

import (
    "strconv"
    "strings"
    "unicode"
)

func validateIPv4(IP string) string {
    nums := strings.Split(IP, ".")
    if len(nums) != 4 {
        return "Neither"
    }
    for _, x := range nums {
        if len(x) == 0 || len(x) > 3 {
            return "Neither"
        }
        if x[0] == '0' && len(x) != 1 {
            return "Neither"
        }
        for _, ch := range x {
            if !unicode.IsDigit(ch) {
                return "Neither"
            }
        }
        num, err := strconv.Atoi(x)
        if err != nil || num > 255 {
            return "Neither"
        }
    }
    return "IPv4"
}

func validateIPv6(IP string) string {
    nums := strings.Split(IP, ":")
    hexdigits := "0123456789abcdefABCDEF"
    if len(nums) != 8 {
        return "Neither"
    }
    for _, x := range nums {
        if len(x) == 0 || len(x) > 4 {
            return "Neither"
        }
        for _, ch := range x {
            if !strings.ContainsRune(hexdigits, ch) {
                return "Neither"
            }
        }
    }
    return "IPv6"
}

func validIPAddress(IP string) string {
    if strings.Count(IP, ".") == 3 {
        return validateIPv4(IP)
    } else if strings.Count(IP, ":") == 7 {
        return validateIPv6(IP)
    } else {
        return "Neither"
    }
}

Explanation

Algorithm

Для проверки адреса IPv4:

Разделить IP на четыре части по разделителю ".".

Проверить каждую подстроку:

Является ли она целым числом между 0 и 255.

Не содержит ли она ведущих нулей (исключение — число "0").

Для проверки адреса IPv6:

Разделить IP на восемь частей по разделителю ":".

Проверить каждую подстроку:

Является ли она шестнадцатеричным числом длиной от 1 до 4 символов.

Если IP не соответствует ни одному из форматов, вернуть "Neither".

😎