leetcode-468 - verify IP address

Continue to create, accelerate growth! This is the 5th day of my participation in the "Nuggets Daily New Plan · June Update Challenge", click to view the event details

topic address

Given a string  queryIP. If it is a valid IPv4 address, return  "IPv4" it; if it is a valid IPv6 address, return  "IPv6" it; if it is not an IP address of the above type, return it  "Neither" .

A valid IPv4 address  is the  “x1.x2.x3.x4” form IP address. where  0 <= xi <= 255 and  xi cannot contain  leading zeros. For example:  “192.168.1.1” ,  “192.168.1.0” is a valid IPv4 address,  “192.168.01.1” is an invalid IPv4 address;  “192.168.1.00” ,  [email protected] is an invalid IPv4 address.

A valid IPv6 address is an “x1:x2:x3:x4:x5:x6:x7:x8” IP address of the form, where:

  • 1 <= xi.length <= 4
  • xi is a  hexadecimal string  that can contain numbers, lowercase English letters (  'a' to  'f' ), and uppercase English letters (  'A' to  'F' ).
  • Leading zeros are allowed in  xi .

For example  "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and  "2001:db8:85a3:0:0:8A2E:0370:7334" is a valid IPv6 address, while  "2001:0db8:85a3::8A2E:037j:7334" and  "02001:0db8:85a3:0000:0000:8a2e:0370:7334" is an invalid IPv6 address.

Example 1:

输入: queryIP = "172.16.254.1"
输出: "IPv4"
解释: 有效的 IPv4 地址,返回 "IPv4"
复制代码

Example 2:

输入: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
输出: "IPv6"
解释: 有效的 IPv6 地址,返回 "IPv6"
复制代码

Example 3:

输入: queryIP = "256.256.256.256"
输出: "Neither"
解释: 既不是 IPv4 地址,又不是 IPv6 地址
复制代码

hint:

  • queryIP Consists of only English letters, numbers, characters  '.' and  ':' .

Problem solving ideas

The given character in this question may have the following 3 situations:

  1. The given characters are valid IPv4 addresses
  2. The given characters are valid IPv6 addresses
  3. The given character is neither a valid IPv4 address nor a valid IPv6 address

Therefore, it is only necessary to judge whether it is a valid IP address according to the given conditions.

Code

var validIPAddress = function(queryIP) {
    const v4Arr = queryIP.split('.')
    const v4Reg = /^[0-9]{1,3}$/g
    const v6Reg = /^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$/g

    if(v4Arr.length === 4){
        for(let i = 0;i<4;i++){
            let item = v4Arr[i]
            v4Reg.lastIndex = 0

            if(!v4Reg.test(item) || (item.length>1 && item[0]==='0') || item*1>255){
                return 'Neither'
            }
        }

        return 'IPv4'
    }
    
    if(v6Reg.test(queryIP)){
        return 'IPv6'
    }

    return 'Neither'
}
复制代码

So far we have completed  leetcode-468-verify IP address

If you have any questions or suggestions, please leave a message to discuss!

Guess you like

Origin juejin.im/post/7103097618921685005