首页 > 代码库 > LeetCode "Restore IP Addresses"

LeetCode "Restore IP Addresses"

It is all about corner cases.

class Solution {public:    vector<string> retv;    bool isValid(string &sub)    {        unsigned cnt = sub.length();        if (cnt == 0 || cnt > 3) return false;        if (cnt == 1) return true;        else        {            if (sub[0] == 0) return false;            if (cnt == 2) return true;            int n = atoi(sub.c_str());            return n < 256;        }            }    void go(string &in, int iStart, int level, string ret)    {        if (iStart >= in.size()) return;        if (level == 3)        {            string slst = in.substr(iStart, in.length() - iStart);                        if (isValid(slst))            {                ret += ".";                ret += slst;                retv.push_back(ret);            }            return;        }        //    len 1        string ret1 = ret;        if(level > 0) ret1 += ".";        ret1 += in[iStart];        go(in, iStart + 1, level + 1, ret1);        //    len 2        string ret2 = ret;        if(level > 0) ret2 += ".";        string sub2 = in.substr(iStart, 2);        if (isValid(sub2))        {            ret2 += sub2;            go(in, iStart + 2, level + 1, ret2);        }        //    len 3        string sub = in.substr(iStart, 3);        if (isValid(sub))        {            string ret3 = ret;            if (level > 0) ret3 += ".";            ret3 += sub;            go(in, iStart + 3, level + 1, ret3);        }    }    vector<string> restoreIpAddresses(string s) {        if (s.empty()) return retv;        go(s, 0, 0, "");        return retv;    }};