File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Given a string containing only digits, restore it by returning all possible
3+ valid IP address combinations.
4+
5+ For example:
6+ Given "25525511135",
7+
8+ return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
9+ """
10+
11+ class Solution :
12+ # @param {string} s
13+ # @return {string[]}
14+ def restoreIpAddresses (self , s ):
15+ res = []
16+ cand = []
17+ self .restore_ip (s , cand , res )
18+ return res
19+
20+ def restore_ip (self , s , cand , res ):
21+ # If more than 4 parts, or 4 parts already but with remaining
22+ # unprocessed sub-string
23+ if len (cand ) > 4 or len (cand ) == 4 and s :
24+ return
25+ elif not s and len (cand ) == 4 :
26+ res .append ('.' .join (cand ))
27+ else :
28+ k = min (3 , len (s )) # Ensures s[:j + 1] won't be duplicate
29+ for j in range (k ):
30+ b = s [:j + 1 ]
31+ if self .is_valid_byte (b ):
32+ cand .append (b )
33+ self .restore_ip (s [j + 1 :], cand , res )
34+ cand .pop ()
35+
36+ def is_valid_byte (self , b ):
37+ if b == '0' :
38+ return True
39+ elif b .startswith ('0' ):
40+ return False
41+ else :
42+ return int (b ) < 256
43+
44+ a = "25525511135"
45+ b = "010010"
46+ s = Solution ()
47+ print (s .restoreIpAddresses (a ))
48+ print (s .restoreIpAddresses (b ))
You can’t perform that action at this time.
0 commit comments