Restore IP Addresses : 0ms

class Solution {
public:
    void helper(int dot, int pos, int len, vector& 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 restoreIpAddresses(string s) {
        int len = s.size();
        vector res;
        if (len < 4)
            return res;
		string target;
        helper(0, 0, len, res, s, target);
        return res;
    }
};

你可能感兴趣的:(algorithm,leetcode,c++)