My simple c++ solution


  • 0
    K
    class Solution {
    public:
    vector<string> restoreIpAddresses(string s) {
       
        vector<string>res;
         if(s.length()==0 || s.length()> 12)return res;
        vector<string>section;
        helper(res, section, s, 0);
        return res;
    }
    void helper(vector<string> & res, vector<string> & section, string s, int start){
    
        if(start==s.length() && section.size()==4){
            string ip="";
            for(auto & str : section)ip+=str+".";
            ip.pop_back();
            res.push_back(ip);
            return;
        }
        string candidate="";
        for(int i=start; i< s.length() && i<start+3; i++){
            candidate+=s[i];
            if(valid(candidate)){
                section.push_back(candidate);
                helper(res, section, s, i+1);
                section.pop_back();
            }
        }
    }
    bool valid(string s) {
        if (s.length() == 0 || s.length() > 3 || (s.length()>1 &&s[0] == '0') || stoi(s) > 255)return false;
        return true;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.