93 Restore IP Addresses

178 篇文章 0 订阅
160 篇文章 0 订阅

1 题目

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

2 尝试解

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        string temp  = "";
        vector<string> result;
        split(s,temp,result,4);
        return result;
    }
    void split(string s,string&temp, vector<string>&result, int bytes){
        if(s.size() > bytes*3 || s.size() < bytes) return;
        if(s.size() == 0){
            temp.pop_back();
            result.push_back(temp);
            return;
        }
        if(s[0] == '0'){  //every 0 must represent a byte by itself
            temp = temp + "0.";
            split(s.substr(1),temp,result,bytes-1);
            return;
        }
        string split_one = temp + s.substr(0,1) + "."; //cut off the first char
        split(s.substr(1),split_one,result,bytes-1);
        if(s.size() > 1){
            string split_two = temp + s.substr(0,2) + "."; //cut off the first two chars
            split(s.substr(2),split_two,result,bytes-1);
        }
        if(s.size() > 2){
            string split_three = temp + s.substr(0,3) + "."; //cut off the first three chars
            if(atoi(s.substr(0,3).c_str()) <= 255){
                split(s.substr(3),split_three,result,bytes-1);
            }

        }
    }
};

3 标准解

class Solution {
public:
    // c++  code
    vector<string> restoreIpAddresses(string s) {
        vector<string> ret;
        string ans;
        
        for (int a=1; a<=3; a++)
        for (int b=1; b<=3; b++)
        for (int c=1; c<=3; c++)
        for (int d=1; d<=3; d++)
            if (a+b+c+d == s.length()) {
                int A = stoi(s.substr(0, a));
                int B = stoi(s.substr(a, b));
                int C = stoi(s.substr(a+b, c));
                int D = stoi(s.substr(a+b+c, d));
                if (A<=255 && B<=255 && C<=255 && D<=255)
                    if ( (ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D)).length() == s.length()+3)
                        ret.push_back(ans);
            }    
        
        return ret;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值