LeetCode:Restore IP Address

93. Restore IP Addresses

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)

Tags: Backtracking String

 

输入一个字符串,要求输出该字符串可能拆分成的ip地址形式。

 

思路:ipv4的地址应该是4段,每段0-255中的一个数。所以考虑4层DFS加一些剪枝条件即可。剪枝条件有:1、取3个字符串stoi作为地址时大于255;2、2位数或者3位数地址段以0开头

另外要检查第四段ip地址为0的情况,防止类似于"0000000"atoi之后也算作0的情况。

 

 1 class Solution {
 2 public:
 3 
 4     bool dfs(string input, int number, string ipAddress, vector<string> &result){
 5         if(input.length() == 0){
 6             return false;
 7         }
 8         if(number == 3){
 9             int addressNumber = stoi(input);
10             if(input[0] == '0'){
11                 if(!(input.length() == 1 && addressNumber == 0))
12                     return false;
13             }
14             if(addressNumber <= 255){
15                 ipAddress = ipAddress + input;
16                 result.push_back(ipAddress);
17                 return true;
18             }else{
19                 return false;
20             }
21         }else{
22             if(input.length() >= 1){
23                 dfs(input.substr(1), number + 1, ipAddress + input.substr(0, 1) + ".", result);
24             }
25             if(input.length() >= 2 && input[0] != '0'){
26                 dfs(input.substr(2), number + 1, ipAddress + input.substr(0, 2) + ".", result);
27             }
28             if(input.length() >= 3 && input[0] != '0'){
29                 int addressNumber = stoi(input.substr(0, 3));
30                 if(addressNumber <= 255){
31                     dfs(input.substr(3), number + 1, ipAddress + input.substr(0, 3) + ".", result);
32                 }
33             }
34         }
35         return true;
36     }
37 
38     vector<string> restoreIpAddresses(string s) {
39         vector<string> result;
40         if(s.length() == 0 || s.length() > 12){
41             return result;
42         }
43         string temp = "";
44         dfs(s, 0, temp, result);
45         return result;
46     }
47 };

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值