Leetcode--Restore IP Addresses

来源:互联网 发布:多位bcd编码 c语言加减 编辑:程序博客网 时间:2024/05/20 16:40

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)

思路:

string类型的长度应该在4~12之间,不在这个范围内的直接返回空

写一个递归函数,每次取字符的情况有三种1)一个字符2)两个字符3)三个字符

判断其对应的数字是否在0~255之间,则继续递归处理。

需要注意的是”00100“对应不到任何ip地址,0.01.0.0不是合法的,对一个IP地址ad1.ad2.ad3.ad4,如果adx的第一字符是0,则它就是0。


class Solution {public:    set<string> res;//set对消除重复集合很方便    void traceback(string s,int i,string temp,int flag)    {        if(flag>4)//flag表示ip地址取了几段了            return ;        if(flag==4&&i>s.size()-1)//已经构成了四段,而且s已经遍历完了,就添加到集合中            res.insert(temp);        else if(flag<4&&i<s.size())        {            string str=s.substr(i,1);            if(atoi(str.c_str())>=0&&atoi(str.c_str())<=255)            {                stringstream  stream;                stream<<(atoi(str.c_str()));                string stmp;                stream>>stmp;                string newtemp=temp+((i==0)?stmp:"."+stmp);                traceback(s,i+1,newtemp,flag+1);            }            if(str!="0")            {                if(i+1<s.size())                    str=s.substr(i,2);                if(atoi(str.c_str())>=0&&atoi(str.c_str())<=255)                {                                    stringstream  stream;                    stream<<(atoi(str.c_str()));                    string stmp;                    stream>>stmp;                    string newtemp=temp+((i==0)?stmp:"."+stmp);                    traceback(s,i+2,newtemp,flag+1);                }                if(str!="00")                {                    if(i+2<s.size())                         str=s.substr(i,3);                    if(atoi(str.c_str())>=0&&atoi(str.c_str())<=255)                    {                        stringstream  stream;                        stream<<(atoi(str.c_str()));                        string stmp;                        stream>>stmp;                        string newtemp=temp+((i==0)?stmp:"."+stmp);                        traceback(s,i+3,newtemp,flag+1);                    }                }            }        }    }    vector<string> restoreIpAddresses(string s) {        if(s.size()>=4&&s.size()<=12)        {            string ss="";            traceback(s,0,ss,0);        }        vector<string> result(res.begin(),res.end());        return result;    }};



0 0
原创粉丝点击