Leetcode -- Restore IP addresses

Source: Internet
Author: User

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given"25525511135",

Return["255.255.11.135", "255.255.111.35"]. (Order does not matter)

The question is to give a string with a reasonable IP address and a list containing all reasonable IP addresses. We know that the IP address is composed of four parts and the reasonable range is 0.0.0.0 ~ 255.255.255.255.

The Code mainly has two functions:

Isvalid -- check whether it is reasonable. If it starts with 0, the string must be 0; otherwise, it must be greater than 0 and less than 255;

DFS-use the Deep Search Method to search for all possible combinations;

Therefore, the DFS method is used to search for all possible combinations. If valid is used during each search to the fourth part, this is a reasonable IP address and is added to the result list.

Pay attention to the details of generating IP addresses and Add. Or something.

The Python code is as follows:

 1 class RestoreIPAddress: 2  3     def isValid(self, src): 4         if src[0] == ‘0‘: 5             return src == ‘0‘ 6         return 255 >= int(src) > 0 7  8     def dfs(self, src, temp, res, count): 9         if count == 3 and self.isValid(src):10             res.append(temp + src)11             return12         for i in range(1, min(4, len(src))):13             sub = src[0:i]14             if self.isValid(sub):15                 self.dfs(src[i:], temp + sub + ‘.‘, res, count + 1)16 17     def restoreIpAddresses(self, s):18         if len(s) < 4 or len(s) > 12:19             return []20         res = []21         self.dfs(s, "", res, 0)22         # print(res)23         return res24 25 p = RestoreIPAddress()26 p.restoreIpAddresses("0000")

 

Leetcode -- Restore IP addresses

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.