468.验证IP地址
链接:468.验证IP地址
难度:Medium
标签:字符串
简介:编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
题解 1 - typescript
- 编辑时间:2021-11-07
- 执行用时:72ms
- 内存消耗:39.5MB
- 编程语言:typescript
- 解法介绍:每一个片段进行解析。
function checkIpv4(query: string) {
  const list = query.split('.');
  if (list.length !== 4) return false;
  for (const section of list) {
    if (
      section === '' ||
      (section.length > 1 && section[0] === '0') ||
      /[a-zA-Z]+/.test(section) ||
      +section >= 256
    )
      return false;
  }
  return true;
}
function checkIpv6(query: string) {
  const list = query.split(':');
  if (list.length !== 8) return false;
  for (const section of list) {
    if (section === '0') continue;
    if (section === '' || section.length > 4 || /[g-zG-Z]+/.test(section)) return false;
  }
  return true;
}
function validIPAddress(queryIP: string): string {
  let ipv4 = false;
  let ipv6 = false;
  for (const c of queryIP) {
    if (c === '.') {
      ipv4 = true;
      break;
    } else if (c === ':') {
      ipv6 = true;
      break;
    }
  }
  if (ipv4 && checkIpv4(queryIP)) return 'IPv4';
  if (ipv6 && checkIpv6(queryIP)) return 'IPv6';
  return 'Neither';
}
题解 2 - typescript
- 编辑时间:2022-05-29
- 执行用时:64ms
- 内存消耗:42.5MB
- 编程语言:typescript
- 解法介绍:遍历,检测。
const ipv4Reg = /^[0-9]+$/;
function _checkIPV4(item: string): boolean {
  if (!ipv4Reg.test(item)) return false;
  if (item.length > 1 && item[0] === '0') return false;
  if (parseInt(item) > 255) return false;
  return true;
}
function checkIPV4(str: string): boolean {
  const items = str.split('.');
  if (items.length !== 4) return false;
  return items.every(_checkIPV4);
}
const ipv6Reg = /^[0-9a-fA-F]*$/;
function _checkIPV6(item: string): boolean {
  if (!ipv6Reg.test(item)) return false;
  if (item.length > 4 || item.length === 0) return false;
  return true;
}
function checkIPV6(str: string): boolean {
  const items = str.split(':');
  if (items.length !== 8) return false;
  return items.every(_checkIPV6);
}
function validIPAddress(queryIP: string): string {
  if (checkIPV4(queryIP)) return 'IPv4';
  if (checkIPV6(queryIP)) return 'IPv6';
  return 'Neither';
}