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)

这道题整了我很久,首先是一个老毛病犯了,又忘了区分字符'0'和数字0了,导致判断的时候出错,还有,最后结果的push

res.push_back( temp.substr(0,temp.size()-1));这样是对的,刚才出错是因为,temp=temp.substr(0,temp.size()-1);res.push_back(temp),这样子回溯的时候,会多删除一个。思路没错,就是因为这两个细节的错误导致这个程序调了很久。

整体思路就是深度优先搜索,首先看到边界条件没,如果没有,就深度搜索:

一开始搜索1个字符和剩下的字符串,判断该字符的index是否越界了,对于剩下的字符串递归;

然后是2个字符和剩下的字符串,判断这2个字符的首字符是否是0,对于剩下的字符串递归;

然后是3个字符和剩下的字符串,判断这3个字符的首字符是否是0,并且这3个字符组成的数字是否小于等于255,对于剩下的字符串递归。

class Solution {
private:
    vector<string> res;
    string temp;
    int lenth;
public:
    bool isValid(string subs)
    {
       
        if(subs[0]=='0'&&subs.size()!=1)
            return false;
        int num;
        stringstream ss(subs);
        ss >> num;
        ss.clear();
        if(num>255)
            return false;
        else
            return true;
    }
    void TestRest(string rests,int count)
    {
        if(count==4)
        {
            if(rests.size()==0)
            {
                res.push_back( temp.substr(0,temp.size()-1));
                return ;
            }
            else
                return;
        }
        else 
        {
            if(rests.size()==0)
                return ;
        }
        string flag;
        for(int i=0;i<3;i++)
        {
            if(i>=rests.size())
                break;
            flag.push_back(rests[i]);
            if(isValid(flag))
            {
                temp+=flag+".";
                TestRest(rests.substr(i+1),count+1);
                temp=temp.substr(0,temp.size()-flag.size()-1);
            }
            else 
                break;
        }
        return ;
        
    }
    vector<string> restoreIpAddresses(string s) {
        string flag;
        lenth=s.size();
        if(lenth>12||lenth<4)
            return res;
        for(int i=0;i<3;i++)
        {
            flag.push_back(s[i]);
            if(isValid(flag))
            {
                temp+=flag+".";
                TestRest(s.substr(i+1),1);
                temp=temp.substr(0,temp.size()-flag.size()-1);
            }
            else 
                break;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/qiaozhoulin/p/4602915.html