Skip to content

Latest commit

 

History

History
56 lines (50 loc) · 1.42 KB

468.验证ip地址.md

File metadata and controls

56 lines (50 loc) · 1.42 KB

468.验证 ip 地址

/*
 * @lc app=leetcode.cn id=468 lang=typescript
 *
 * [468] 验证IP地址
 */

// @lc code=start
function validIPAddress(queryIP: string): string {}
// @lc code=end

解法 1: 分类讨论

function validIPAddress(queryIP: string): string {
  if (new Set(queryIP).has('.')) {
    const nums = queryIP.split('.')
    if (nums.length !== 4) return 'Neither'
    for (let num of nums) {
      if (num.length > 3 || num.length === 0) return 'Neither'
      if (num[0] === '0' && num.length > 1) return 'Neither'
      for (let i = 0; i < num.length; i++) {
        if (!/[0-9]/.test(num[i])) return 'Neither'
      }
      if (Number(num) >= 0 && Number(num) <= 255) continue
      return 'Neither'
    }
    return 'IPv4'
  } else {
    const nums = queryIP.split(':')
    if (nums.length !== 8) return 'Neither'
    for (let num of nums) {
      if (num.length > 4 || num.length === 0) return 'Neither'
      for (let i = 0; i < num.length; i++) {
        if (!/[0-9a-fA-F]/.test(num[i])) return 'Neither'
      }
    }
    return 'IPv6'
  }
}

Case

test.each([
  { input: { queryIP: '172.16.254.1' }, output: 'IPv4' },
  { input: { queryIP: '2001:0db8:85a3:0:0:8A2E:0370:7334' }, output: 'IPv6' },
  { input: { queryIP: '256.256.256.256' }, output: 'Neither' },
])('input: queryIP = $input.queryIP', ({ input: { queryIP }, output }) => {
  expect(validIPAddress(queryIP)).toEqual(output)
})