LeetCode 复原IP地址(探索字节跳动)

题目描述

 

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

示例:

输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]

 

解题思路

 

递归地搜索地址段,对于每个地址首先判断其是否为'0',若为0则其必须作为一个单独的地址段,接下来只能判断其下一个地址段;若不为0,则依次取1-3位数字组成的数作为地址段,注意在取3位的时候要保证其小于256,否则停止加入地址。最后在地址段总数为4且已遍历到字符串末尾时,将其加入到结果集合中。

 

代码

 

 1 class Solution {
 2 public:
 3     vector<string> restoreIpAddresses(string s) {
 4         vector<string> res;
 5         findIp(s, 0, 0, "", res);
 6         return res;
 7     }
 8     void findIp(string s, int idx, int part, string temp, vector<string> &res){
 9         if(part == 4 && idx == s.length())
10             res.push_back(temp.substr(0, temp.length() - 1));
11         else if(part < 4){
12             if(s[idx] == '0'){
13                 findIp(s, idx + 1, part + 1, temp + "0.", res);
14                 return;
15             }
16             for(int i = 1; i < 4; i++){
17                 if(idx + i - 1 == s.length()) return;
18                 int address = stoi(s.substr(idx, i));
19                 if(address < 256)
20                     findIp(s, idx + i, part + 1, temp + to_string(address) + ".", res);
21             }
22         }
23     }
24 };

 

posted @ 2018-12-20 15:10  FlyingWarrior  阅读(1254)  评论(0编辑  收藏  举报