My simple C++ code 4ms 0(1)


  • 0
    L
    class Solution {
    public:
        vector<string> restoreIpAddresses(string s) 
        {
            vector<string> ret;
            if(s.size()>12||s.size()<4)return ret;
            string first,second,third,forth;
            for(int i=0;i<3;i++){
                first=s.substr(0,i+1);
                if(!if_valid(first))continue;
                   for(int j=i+1;j<i+4&&j<s.size();j++){
                      second=s.substr(i+1,j-i);
                      if(!if_valid(second))continue;
                         for(int k=j+1;k<j+4&&k<s.size();k++){
                            third=s.substr(j+1,k-j);
                            if(!if_valid(third))continue;
                            forth=s.substr(k+1,s.size()-k-1);
                            if(!if_valid(forth))continue;
                            else ret.push_back(first+"."+second+"."+third+"."+forth);
                         }
                   }
            }
            return ret;
        }
        bool if_valid(string s)
        {
            if(s.size()==0||s.size()>3||stoi(s)>255||(s[0]=='0'&&s.size()>1))
            return false;
            else return 1;
        }
    };

Log in to reply
 

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