Advertisement
jinhuang1102

93. Restore IP Addresses

Nov 11th, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. class Solution:
  2.     def isValid(self, s):
  3.         if not s or len(s) > 3 or (len(s) > 1 and s[0] == '0'):
  4.             return False
  5.         else:
  6.             res = int(s)
  7.             return res <= 255 and res >=0
  8.    
  9.     def backtrack(self, s, k, addr, res):
  10.         if k == 0:
  11.             if not s:
  12.                 res.append(addr)
  13.                 return
  14.  
  15.         else:
  16.             for i in range(1, 4):
  17.                 if len(s) > i and self.isValid(s[:i]):
  18.                     if k == 1:
  19.                         self.backtrack(s[i:], k-1, addr + s[:i], res)
  20.                     else:
  21.                         self.backtrack(s[i:], k-1, addr + s[:i] + "." , res)  
  22.         return        
  23.                
  24.     def restoreIpAddresses(self, s):
  25.         """
  26.        :type s: str
  27.        :rtype: List[str]
  28.        """
  29.         res = []
  30.         self.backtrack(s, 4, "", res)
  31.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement