[leetcode] Restore IP Addresses restore IP address
Given a string containing only a number, restore it and return all possible IP address formats.
Example:
Input: "25525511135" output:["255.255.11.135", "255.255.111.35"]
The IP address consists of 32-bit binary numbers, for ease of use, often in the form of XXX.XXX.XXX.XXX, each group of XXX represents 10 binary numbers less than or equal to 255. So there are four paragraphs in total IP address, each paragraph may have one, two or three bits, the range is [0, 255], the topic clearly indicates that the input string contains only numbers, so when a segment is three, we have to determine whether it crosses the border (>255), and it is important that when there is only one, 0 can be a section, if there are two or three bits, such as 00, 01, 001, 011, 000, etc. are not legal, so we still need a decision function to determine whether a string is legitimate. This problem can also be seen as the segmentation of strings, in the input string to add three points, the string is divided into four paragraphs, each paragraph must be legal, for all possible situations. We use K to indicate the number of segments currently required, if k = 0, it means that three points have been added to complete, four paragraphs have been formed, if the string is just empty, then the results of the current good saved. If k! = 0, then for each paragraph, we use one, two, three bit to try, respectively, judge its incompatibility, if it is legal, then call DFS recursion continue to divide the remaining string, finally and find out all the legal combination, the code is as follows:
- class Solution (object):
- def restoreipaddresses (self, s):
- """
- : Type S:str
- : Rtype:list[str]
- """
- if s = = "" or len (s) > or len (s) < 4:
- return []
- result = []
- Parts = 4
- Item = ""
- Self. DFS (S, parts, item, result)
- return Result
- def DFS (self, s, parts, item, result):
- if parts = = 0:#全部取完
- if s = = "":
- Result.append (item)
- Else:
- for I in range (1, 4):
- if len (s) >= i and Self.isvalid (S[:i]):
- if parts = = 1:#最后一部分
- Self. DFS (s[i:], parts-1, item+s[:i], result)
- else:#开始部分
- Self. DFS (s[i:], parts-1, item+s[:i]+".", result)
- def IsValid (self, s):
- if s = = "" or len (s) > 3 or (len (s) > 1 and s[0 ] = = "0"):
- return False
- int_s = Int (s)
- return int_s <= 255 and int_s >= 0
-
[Leetcode] Restore IP Addresses Restore IP address