Advertisement
Guest User

Restore IP Addresses

a guest
Feb 5th, 2021
171
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def restoreIpAddresses(s: str):
  2.     def backtrack(s, integers, path, result):
  3.         if integers == 4:
  4.             if not s:
  5.                 # we have 4 integers and
  6.                 # we've used all the digits in s
  7.                 result.append(path[:-1])
  8.             return
  9.         for i in range(1, 4):
  10.             if i > len(s):
  11.                 continue
  12.             # integer cannot have leading 0s
  13.             if i > 1 and s[0] == '0':
  14.                 continue
  15.             # integer must be less than 255
  16.             if i > 2 and int(s[:3]) > 255:
  17.                 continue
  18.             backtrack(s[i:], integers+1, path + s[:i] + '.', result)
  19.        
  20.     result = []
  21.     backtrack(s, 0, '', result)
  22.     return result
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement