Created
August 26, 2019 14:39
-
-
Save priyankvex/9e47408537c04e216ad09c2f16b0b761 to your computer and use it in GitHub Desktop.
Valid IP addresses possible
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
count = [] | |
def solve(self, s): | |
self.helper(s, 0, 0, 0, []) | |
addresses = [] | |
for a in self.count: | |
prev = None | |
add = None | |
for c in a: | |
if not add: | |
add = s[0:c + 1] | |
else: | |
add += "." | |
add += s[prev + 1:c + 1] | |
prev = c | |
addresses.append(add) | |
return addresses | |
def helper(self, s, part_count, start_index, count, points): | |
n = len(s) | |
if part_count == 4 and start_index == n: | |
self.count.append(points) | |
if start_index == n: | |
return 0 | |
for i in range(start_index, n): | |
cur = s[start_index:i+1] | |
if self.is_valid(cur): | |
points.append(i) | |
self.helper(s, part_count + 1, i+1, count, points[:]) | |
points.pop() | |
def is_valid(self, s): | |
if len(s) > 1 and s[0] == '0': | |
return False | |
n = int(s) | |
if n > 255 or n < 0: | |
return False | |
return True | |
if __name__ == "__main__": | |
s = "00000" | |
ans = Solution().solve(s) | |
print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment