Featured image of post Validate IP Address

Validate IP Address

468. 验证IP地址

分析

  1. IPv4 的验证规则:

    • 总共有 4 段,以 . 分隔
    • 每一段不能为空,也不能超过 4
    • 每一段不能有前导零(如 01 是非法的)
    • 每一段只能包含数字字符
    • 每一段是 0255 的十进制数字
  2. IPv6 的验证规则:

    • 总共有 8 段,以 : 分隔
    • 每一段不能为空,也不能超过 4
    • 每一段是 1 ~ 4 个十六进制字符(0 - 9, a - f, A - F

时间复杂度

时间复杂度 O(n)

空间复杂度

空间复杂度为 O(1)

C++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution
{
public:
    // 字符串分割函数
    std::vector<std::string> split(std::string ip, char sep)
    {
        std::vector<std::string> items;
        for (int i = 0; i < ip.size(); ++ i)
        {
            int j = i;
            std::string item;
            // 提取每段内容直到遇到分隔符
            while (ip[j] != sep)
                item += ip[j ++ ];
            items.push_back(item);
            i = j;
        }
        return items;
    }

    // IPv4 验证函数
    std::string check_ipv4(std::string ip)
    {
        std::vector<std::string> items = split(ip + '.', '.'); // 加一个终止符避免遗漏最后一段
        if (items.size() != 4) return "Neither";
        for (auto item : items)
        {
            if (item.empty() || item.size() > 3) return "Neither";
            if (item.size() > 1 && item[0] == '0') return "Neither";  // 不允许前导0
            for (auto c : item)
                if (c < '0' || c > '9') return "Neither";
            if (std::stoi(item) > 255) return "Neither";
        }
        return "IPv4";
    }

    // IPv6 合法字符判断
    bool check_ch(char c)
    {
        if (c >= '0' && c <= '9') return true;
        if (c >= 'a' && c <= 'f') return true;
        if (c >= 'A' && c <= 'F') return true;
        return false;
    }

    // IPv6 验证函数
    std::string check_ipv6(std::string ip)
    {
        std::vector<std::string> items = split(ip + ':', ':');
        if (items.size() != 8) return "Neither";
        for (auto item : items)
        {
            if (item.empty() || item.size() > 4) return "Neither";
            for (auto c : item)
                if (!check_ch(c)) return "Neither";
        }
        return "IPv6";
    }

    // 主函数,根据分隔符判断格式
    string validIPAddress(string queryIP)
    {
        if (queryIP.find('.') != -1 && queryIP.find(':') != -1) return "Neither"; // 同时包含 . 和 :
        if (queryIP.find('.') != -1) return check_ipv4(queryIP);
        if (queryIP.find(':') != -1) return check_ipv6(queryIP);
        return "Neither";
    }
};
Built with Hugo
Theme Stack designed by Jimmy