代码拉取完成,页面将自动刷新
<?php
// https://leetcode-cn.com/problems/validate-ip-address/solution/yan-zheng-ip-di-zhi-by-leetcode/
class Solution {
public function validateIPv4($IP)
{
// 以.为分隔符拆分
$nums = explode('.', $IP);
foreach ($nums as $x) {
// Validate integer in range (0, 255):
// 1. length of chunk is between 1 and 3
// 校验每一部分长度为1到3
if (strlen($x) == 0 || strlen($x) > 3) {
return "Neither";
}
// 2. no extra leading zeros
// 以0开头开始的 只能够长度为1 0.0.0.0 不能为192.01.2.1这种
if (strpos($x, '0') === 0 && strlen($x) != 1) {
return "Neither";
}
// 3. only digits are allowed
// 验证每个字符是否为数字
foreach (str_split($x, 1) as $ch) {
if (! is_numeric($ch)) {
return "Neither";
}
}
// 4. less than 255
// 是否超过255
if (intval($x) > 255) {
return "Neither";
}
}
return "IPv4";
}
public function validateIPv6($IP)
{
// 以:为分隔符拆分
$nums = explode(':', $IP);
// 允许的字符表
$hexdigits = array(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f',
'A', 'B', 'C', 'D', 'E', 'F'
);
foreach ($nums as $x) {
// Validate hexadecimal in range (0, 2**16):
// 1. at least one and not more than 4 hexdigits in one
// 校验每一部分长度为1到4
if (strlen($x) == 0 || strlen($x) > 4) {
return "Neither";
}
// 2. only hexdigits are allowed: 0-9, a-f, A-F
// 校验字符是否在允许的字符表中
foreach (str_split($x, 1) as $ch) {
if (! in_array($ch, $hexdigits, true)) {
return "Neither";
}
}
}
return "IPv6";
}
public function validIPAddress($IP) {
if (count(explode('.', $IP)) == 4) {
return $this->validateIPv4($IP);
}
if (count(explode(':', $IP)) == 8) {
return $this->validateIPv6($IP);
}
return "Neither";
}
}
var_dump((new Solution())->validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"));
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。