【算法】判断IP地址是不是合法的,包含IPv4和IPv6

1. 概述

类似题目:

LeetCode468: https://leetcode.com/problems/validate-ip-address/

LeetCode93: https://leetcode.com/problems/restore-ip-addresses/


编写一个函数来验证输入的每个字符串是否是有效的IPv4或IPv6地址。
  • 如果是有效的 IPv4 地址,返回 “IPv4”;
  • 如果是有效的 IPv6 地址,发挥 “IPv6”;
  • 如果不是上述类型的IP地址,返回 “Neither”。

IPv4地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 ~ 255,用 (“.”) 分割,比如:
172.16.254.1

同时,IPv4地址内的数不会以0开头。比如,地址 172.16.254.1 是不合法的。

IPv6地址由8组16进制的数字来表示,每组表示16比特。这些数字通过 (“:”) 分割,比如:2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以0开头的数字,字母可以使用大写,也可以是小写。所以,2001:0db8:85a3:0000:0000:8A2E:0370:7334 也是一个有效的 IPv6 地址(即,忽略0开头,忽略大小写)。

然而,我们不能因为某个组的值为0,而使用一个空的组,以至于出现(::)的情况。比如,2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。

同时,在IPv6地址中,多余的0也是不被允许的。比如,02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。

例子

输入:IP = “172.16.254.1”
输出:“IPv4”
解释:有效的 IPv4 地址,返回 “IPv4”


2. 代码及测试

Java

方法1

class Solution {
    public String validIPAddress(String queryIP) {
        if (queryIP == null || queryIP.length() < 1) return "Neither";
        int n = queryIP.length();
        int index = 0;
        while (index < n && queryIP.charAt(index) != '.' && queryIP.charAt(index) != ':') index++;
        if (index == n) return "Neither";
        int cnt = 0;
        if (queryIP.charAt(index) == '.') {
            // check IPv4
            index = 0;
            int left = 0;
            while (index < n) {
                while (index < n && queryIP.charAt(index) != '.') index++;
                String str = queryIP.substring(left, index);
                if (cnt > 4 || str == null || str.length() < 1 || str.length() > 3 || (str.length() > 1 && str.charAt(0) == '0')) return "Neither";
                for (int i = 0; i < str.length(); i++) {
                    if (str.charAt(i) < '0' || str.charAt(i) > '9') return "Neither";
                }
                int val = Integer.parseInt(str);
                if (val < 0 || val > 255) return "Neither";
                cnt++;
                left = index + 1;
                index++;
            }
            if (cnt == 4 && index == n + 1) return "IPv4";
        } else {
            // check IPv6
            index = 0;
            int left = 0;
            while (index < n) {
                while (index < n && queryIP.charAt(index) != ':') index++;
                String str = queryIP.substring(left, index);
                if (cnt > 8 || str == null || str.length() < 1 || str.length() > 4) return "Neither";
                for (int i = 0; i < str.length(); i++) {
                    if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9') && !(str.charAt(i) >= 'a' && str.charAt(i) <= 'f') && !(str.charAt(i) >= 'A' && str.charAt(i) <= 'F')) return "Neither";
                }
                cnt++;
                left = index + 1;
                index++;
            }
            if (cnt == 8 && index == n + 1) return "IPv6";
        }
        return "Neither";
    }
}

方法2

class Solution {
    public String validIPAddress(String queryIP) {
        if (queryIP == null || queryIP.length() < 1) {
            return "Neither";
        }
        queryIP = queryIP.toLowerCase();
        int n = queryIP.length();
        if (queryIP.charAt(n - 1) == '.' || queryIP.charAt(n - 1) == ':') {
            return "Neither";
        }
        int index = 0;
        while (index < n && queryIP.charAt(index) != '.' && queryIP.charAt(index) != ':') index++;
        if (index == n) return "Neither";
        if (queryIP.charAt(index) == '.') {
            // check IPv4
            String[] strs = queryIP.split("\\.");
            if (strs.length != 4) return "Neither";
            for (int i = 0; i < 4; i++) {
                if (strs[i].length() < 1 || strs[i].length() > 3 || (strs[i].length() > 1 && strs[i].charAt(0) == '0')) return "Neither";
                for (int j = 0; j < strs[i].length(); j++) {
                    if (strs[i].charAt(j) < '0' || strs[i].charAt(j) > '9') return "Neither";
                }
                int val = Integer.parseInt(strs[i]);
                if (val < 0 || val > 255) return "Neither";
            }
            return "IPv4";
        } else {
            // check IPv6
            String[] strs = queryIP.split(":");
            if (strs.length != 8) return "Neither";
            for (int i = 0; i < 8; i++) {
                if (strs[i].length() < 1 || strs[i].length() > 4) return "Neither";
                for (int j = 0; j < strs[i].length(); j++) {
                    if (!(strs[i].charAt(j) >= '0' && strs[i].charAt(j) <= '9') && !(strs[i].charAt(j) >= 'a' && strs[i].charAt(j) <= 'f')) {
                        return "Neither";
                    }
                }
            }
            return "IPv6";
        }
    }
}

C++

方法1

class Solution {
public:
    string validIPAddress(string queryIP) {
        int n = queryIP.size();
        if(n < 7) return "Neither";
        int index = 0;
        while (index < n && queryIP[index] != '.' && queryIP[index] != ':') index++;
        if (index == n) return "Neither";
        int cnt = 0;
        if (queryIP[index] == '.') {
            // check IPv4
            index = 0;
            int left = index;
            while (index < n) {
                while (index < n && queryIP[index] != '.') index++;
                string t = queryIP.substr(left, index - left);
                if (cnt > 4 || t.empty() || (t.size() > 1 && t[0] == '0') || t.size() > 3) return "Neither";
                for (char c: t) {
                    if (c < '0' || c > '9') return "Neither";
                }
                int val = stoi(t);
                if (val < 0 || val > 255) return "Neither";
                cnt++;
                left = index + 1;
                index++;
            }
            if (cnt == 4 && index == n + 1) return "IPv4";
        } else {
            // check IPv6
            index = 0;
            int left = index;
            while (index < n) {
                while (index < n && queryIP[index] != ':') index++;
                string t = queryIP.substr(left, index - left);
                if (cnt > 8 || t.empty() || t.size() > 4) return "Neither";
                for (char c: t) {
                    if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return "Neither";
                }
                cnt++;
                left = index + 1;
                index++;
            }
            if (cnt == 8 && index == n + 1) return "IPv6";
        }
        return "Neither";
    }
};

方法2

class Solution {
public:
    string validIPAddress(string IP) {
        istringstream is(IP);
        string t = "";
        int cnt = 0;
        if (IP.find(':') == string::npos) { // Check IPv4
            while (getline(is, t, '.')) {
                ++cnt;
                if (cnt > 4 || t.empty() || (t.size() > 1 && t[0] == '0') || t.size() > 3) return "Neither";
                for (char c: t) {
                    if (c < '0' || c > '9') return "Neither";
                }
                int val = stoi(t);
                if (val < 0 || val > 255) return "Neither";
            }
            return (cnt == 4 && IP.back() != '.') ? "IPv4" : "Neither";
        } else { // Check IPv6
            while (getline(is, t, ':')) {
                ++cnt;
                if (cnt > 8 || t.empty() || t.size() > 4) return "Neither";
                for (char c: t) {
                    if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return "Neither";
                }
            }
            return (cnt == 8 && IP.back() != ':') ? "IPv6" : "Neither";
        }
    }
};
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值