首页 > 其他 > 详细

LeetCode "Restore IP Addresses"

时间:2014-08-02 12:39:03      阅读:307      评论:0      收藏:0      [点我收藏+]

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;
    }
};

LeetCode "Restore IP Addresses",布布扣,bubuko.com

LeetCode "Restore IP Addresses"

原文:http://www.cnblogs.com/tonix/p/3886688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!