Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
910 B
2
Indexable
Never
class Solution {
public:
    void solve(int i,int dot,string &path,string &s,vector<string>&res){
        if(dot<0) return;
        if(i==s.size()){
            if(dot==0) res.push_back(path);
            return;
        }
        for(int len=1;len<=3 && i+len<=s.size();len++){ //possible lengths in an IP segment ,<= because of substr
            string w=s.substr(i,len);
            if(stoi(w)>255 ||(w.size()>1 && w[0]=='0')) return;//invalid segment
            
            string npath; //npath is the new segment
            if(!path.empty()){
                npath=path+"."+w;
            }else{
                npath=w;
            }

            solve(i+len,dot-1,npath,s,res);
            
        }
    }

    vector<string> restoreIpAddresses(string s) {
        vector<string>res;
        string path="";
        solve(0,4,path,s,res);
        return res;
    }
};
Leave a Comment