MediumString

Validate IP Address

LeetCode
1 approach, code in all languages

Given a string, decide whether it is a valid IPv4 address, a valid IPv6 address, or neither. An IPv4 address is four decimal groups separated by dots, where each group is a number from 0 to 255 with no leading zeros (except the single digit 0). An IPv6 address is eight groups separated by colons, where each group has one to four hexadecimal digits and both letter cases are allowed.

Return "IPv4" for a valid IPv4 string, "IPv6" for a valid IPv6 string, and "Neither" for anything that does not fit either format. Empty groups and trailing separators are invalid.

Example 1

Input: queryIP = "10.0.1.38"

Output: "IPv4"

Four groups, each between 0 and 255 with no leading zeros, so it is a valid IPv4 address.

Example 2

Input: queryIP = "2001:0db8:85a3:0:0:8a2e:0370:7334"

Output: "IPv6"

Eight colon-separated groups, each with one to four hexadecimal digits, so it is a valid IPv6 address.

Constraints

  • 1 ≤ queryIP.length ≤ 40
  • queryIP consists of English letters, digits, and the characters '.' and ':'
  • The answer is exactly one of "IPv4", "IPv6", or "Neither"
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now