Restore IP Addresses

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

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


解法:

     我们知道一个合法的IP地址不超过12个字符,因此我们可以遍历每个逗号,即三个for循环,搜索次数不超过12^3=1728次。所以可以暴力解决,疑惑为什么这题是medium。同是medium,但难度与super ugly number没法比。代码如下:

class Solution {
public:
    bool check(string s)
    {
        if(s.size()==1||(0<s.size()&&s.size()<=3&&s[0]!='0'))
        {
            stringstream ss(s);
            int n;
            ss>>n;
            if(n<=255)return true;
        }
        return false;
    }
    vector<string> restoreIpAddresses(string s) {
        vector<string> t;
          if(s.size()>12)return t;
        for(int i=0;i<s.size();++i)
            for(int j=i+1;j<s.size();++j)
                for(int k=j+1;k<s.size()-1;++k)
                {
                    string temp1;
                    for(int n=0;n<=i;++n)
                        temp1+=s[n];
                    if(!check(temp1))continue;
                    string temp2;
                    for(int n=i+1;n<=j;++n)
                        temp2+=s[n];
                    if(!check(temp2))continue;
                    string temp3;
                    for(int n=j+1;n<=k;++n)
                        temp3+=s[n];
                    if(!check(temp3))continue;
                    string temp4;
                    for(int n=k+1;n<s.size();++n)
                        temp4+=s[n];
                    if(!check(temp4))continue;
                    t.push_back(temp1+"."+temp2+"."+temp3+"."+temp4);
                    
                }
        return t;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值