关闭

Restore IP Addresses : 0ms

标签: leetcodec++
251人阅读 评论(0) 收藏 举报
分类:
class Solution {
public:
    void helper(int dot, int pos, int len, vector<string>& res, string& s, string& target) {
        int deltaLen = len - pos;
        if (dot == 3) {
			string tmp = s.substr(pos, deltaLen);
			int num = atoi(tmp.c_str());
            if (deltaLen < 4 && deltaLen > 0 &&  num < 256) {
				if ((num > 0 && tmp[0] == '0') || (num == 0 && tmp.size() > 1))
					return ;
				target += tmp;
                res.push_back(target);
				target.erase(target.end()-deltaLen, target.end());
			}
            return ;
        }
        
        if (deltaLen < (3 - dot + 1) * 1 || deltaLen > (3 - dot + 1) * 3)
            return ;
        
        for (int i = pos; i < pos + 3 && i < len; ++ i) {
			int num = atoi(s.substr(pos, i-pos+1).c_str());
			if (num == 0) {
				target += "0.";
				helper(dot+1, i+1, len, res, s, target);
				target.erase(target.end()-2, target.end());
				break;
			}
            else if (num < 256) {
				target += s.substr(pos, i-pos+1);
				target += '.';
                helper(dot+1, i+1, len, res, s, target);
				target.erase(target.end() - (i-pos+2), target.end());
            }
        }
    }
    
    vector<string> restoreIpAddresses(string s) {
        int len = s.size();
        vector<string> res;
        if (len < 4)
            return res;
		string target;
        helper(0, 0, len, res, s, target);
        return res;
    }
};

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:37357次
    • 积分:889
    • 等级:
    • 排名:千里之外
    • 原创:48篇
    • 转载:1篇
    • 译文:0篇
    • 评论:6条
    文章分类
    最新评论