Teaching Kids Programming: Videos on Data Structures and Algorithms
Given a string s, return whether it’s an IPv4 address. IPv4 addresses must follow the format A.B.C.D, where A, B, C, and D are numbers between 0 and 255. Zero-prefixed numbers, such as 01 and 065, are not allowed, except for 0 itself.
Constraints
n ≤ 100 where n is the length of s
Example 1
Input
s = “0.0.0.0”
Output
True
Example 2
Input
s = “0.1.2.255”
Output
True
Example 3
Input
s = “0.1.2.256”
Output
False
Valid IPv4 Address String Validation Algorithm
First, split the string by ‘.’ delimiter. Fail the validation if the array is not size 4. Then we go through each group – check if they are numeric. And also the value should be within 0 to 255. A special case to check is that when it is zero, it should be only represented by a single ‘0’.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution: def solve(self, s): arr = s.split('.') if len(arr) != 4: return False for i in arr: if not i.isnumeric(): return False a = int(i) if a < 0 or a > 255: return False if a == 0 and i != '0': return False return True |
class Solution: def solve(self, s): arr = s.split('.') if len(arr) != 4: return False for i in arr: if not i.isnumeric(): return False a = int(i) if a < 0 or a > 255: return False if a == 0 and i != '0': return False return True
Time complexity O(N) where N is the length of the characters in the string. The space complexity is also O(N) as we are using an array to keep the results of the split.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Count the Repeated K-Length Substrings
Next Post: Teaching Kids Programming - Compute the Hamming Distance of Two Integers