3ms brute-force c++ solution


  • 0
    T

    It's not necessary to use any algorithm because the complexity can be treated as constant

        vector<string> restoreIpAddresses(string s) {
            vector<string> result;
            for(int i=1; i<=3 && i<s.length(); i++) {
                for(int j=1; j<=3&&i+j<s.length(); j++) {
                    for(int k=1; k<=3&&i+j+k<s.length(); k++) {
                        int a = atoi(s.substr(0, i).c_str());
                        int b = atoi(s.substr(i, j).c_str());
                        int c = atoi(s.substr(i+j, k).c_str());
                        int d = atoi(s.substr(i+j+k).c_str());
                        if(a<=255 && b<=255 && c<=255 && d<=255 && to_string(a)==s.substr(0, i) && to_string(b) == s.substr(i, j) && to_string(c) == s.substr(i+j, k) && to_string(d) == s.substr(i+j+k)) {
                            string ip=s.substr(0, i)+"."+s.substr(i, j)+"."+s.substr(i+j, k)+"."+s.substr(i+j+k);
                            if(find(result.begin(), result.end(), ip)==result.end())
                                result.push_back(ip);   
                        }
                    }
                }
            }
            return result;
        }
    

Log in to reply
 

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