题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
package main import "strings" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ func isValidIpv4(segs []string) bool { if len(segs) != 4 { return false } for _, seg := range segs { if seg < "0" || seg > "255" || (seg >= "00" && seg <= "099") { return false } } return true } func isValidIpv6Seg(seg string) bool { if seg == "" || len(seg) > 4 { return false } validC := "0123456789abcdefABCDEF" res := make(map[byte]bool, 0) for _, tc := range []byte(validC) { res[tc] = true } for _, c := range []byte(seg) { if _, ok := res[c]; !ok { return false } } return true } func isValidIpv6(segs []string) bool { if len(segs) != 8 { return false } for _, seg := range segs { if !isValidIpv6Seg(seg) { return false } } return true } func solve(IP string) string { // write code here isV4 := isValidIpv4(strings.Split(IP, ".")) if isV4 { return "IPv4" } isV6 := isValidIpv6(strings.Split(IP, ":")) if isV6 { return "IPv6" } return "Neither" }