Clean solution in C++, without any explanation


  • 1
    class Solution {
    private:
        int sLen;
        void search(const string& s, int pos, int k, string path, vector<string>& v) {
            int len = s.length();
            if(k == 0) { if(pos == len) { path.pop_back(); v.push_back(path); } return ; }
            for(int l = 1; l <= min(3, len-pos); ++l) {
                string t = s.substr(pos, l);
                if(stoi(t) < 256) search(s, pos+l, k-1, path+t+".", v);
                if(s[pos] == '0') break;
            }
        }
    public:
        vector<string> restoreIpAddresses(string s) {
            vector<string> v;
            if(s.length() > 12) return v;
            search(s, 0, 4, "", v);
            return v;
        }
    };
    

Log in to reply
 

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