C++, with comments (3ms)


  • 0
    B
    class Solution {
    public:
        vector<string> restoreIpAddresses(string s) {
            // Should have [4-12] chars
            if(s.length() < 4 || s.length() > 12) return {};
            vector<string> result;
            // Edge case we know the answer
            if(s.length() == 4){
                result.push_back(string(1,s[0])+'.'+s[1]+'.'+s[2]+'.'+s[3]);
                return result;
            }
            int i,j,k,l;
            // 1. Find all possible lengths of numbers with
            // total length equal to s.length
            // 2. filter acceptable numbers and add it to result vector
            for(i=0;i<3;++i){
                for(j=i+1;j< 3+i+1;++j){
                    for(k=j+1;k<3+j+1;++k){
                        for(l=k+1;l<3+k+1;++l){
                            if(l!= s.length() -1) continue;
                            // Check if each number is within the bounds
                            if( getNumAndCheck(s, 0, i+1) && getNumAndCheck(s, i+1, j-i) && getNumAndCheck(s, j+1, k-j) && getNumAndCheck(s, k+1, l-k) ) {
                            result.push_back(s.substr(0,i+1)+'.'+s.substr(i+1, j-i)+'.'+s.substr(j+1, k-j)+'.'+s.substr(k+1, l-k));
                            }
                        }
                    }
                }
            }
            return result;
        }
        bool getNumAndCheck(string &str, int s, int len){
            string tempstr = str.substr(s,len);
            int tempInt = stoi(tempstr);
            // Check is number in bound and trailing 0 nums are rejected
            if(tempInt < 0 || tempInt>255 || (len ==2 && tempInt<10) || (len ==3 && tempInt<100)) return false;
            return true;
        }
    };
    

Log in to reply
 

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