Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,
172.16.254.1
;
Besides, leading zeros in the IPv4 is invalid. For example, the address
172.16.254.01
is invalid.
IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address
2001:0db8:85a3:0000:0000:8a2e:0370:7334
is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so2001:db8:85a3:0:0:8A2E:0370:7334
is also a valid IPv6 address(Omit leading zeros and using upper cases).
However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example,
2001:0db8:85a3::8A2E:0370:7334
is an invalid IPv6 address.
Besides, extra leading zeros in the IPv6 is also invalid. For example, the address
02001:0db8:85a3:0000:0000:8a2e:0370:7334
is invalid.
Note: You may assume there is no extra space or special characters in the input string.
寫一個程式去判斷輸入字串是否為合法的IPv4位址、IPv6位址還是兩者皆否。
IPv4位址的規範是dot-decimal,其中包含四個0到255的十進位數字並使用小數點來分開。例如:
172.16.254.1
。
另外,前導零在IPv4中是不合法的。例如
172.16.254.01
這個位址是不合法的。
IPv6用八組四個16進位的字(每組代表16 bits)表示。每組之間使用冒號(":")分開。例如,
2001:0db8:85a3:0000:0000:8a2e:0370:7334
是合法的位址。我們可以省略四個16進制的數字中的前導零,也可以將小寫字母改為大寫,因此2001:db8:85a3:0:0:8A2E:0370:7334
也是一個合法IPv6的位址(省略前導零和使用大寫字母)。
然而,為求簡單,我們不允許使用兩個冒號取代連續值為零的組別,例如
2001:0db8:85a3::8A2E:0370:7334
是不合法的IPv6位址。
此外,在IPv6中多餘的前導零是不合法的。例如:
02001:0db8:85a3:0000:0000:8a2e:0370:7334
是不合法的位址。
提示: 你可以假設輸入字串中沒有多餘的空白或是特別字元。
.
:
辨識)LeetCode
C++