lintcode:Restore IP Addresses

504 篇文章 0 订阅
66 篇文章 0 订阅
Restore IP Addresses
30:00

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

Given "25525511135", return

[
  "255.255.11.135",
  "255.255.111.35"
]

Order does not matter.


class Solution {
    
private:

    int _min(int a, int b)
    {
        if (a <= b)
            return a;
        return b;
    }

    string getIP(vector<int> &curTry) {
        
        string ret = "";
        for (int i=0; i<4; i++)
        {
            ret = ret + to_string(curTry[i]);
            
            if (i != 3)
                ret = ret + ".";
        }
        return ret;
    }

    bool isValidNum(long num) {
        
        if (num >= 0 && num <= 255) //0 也是可以的
            return true;
        return false;
    }

    void restoreIpAddressesHelper(string &s, int curIdx, vector<int> &curTry, vector<string> &retVtr)
    {
        if (curTry.size() == 4)
        {
            if (curIdx == s.size())
            {
                string strIP = getIP(curTry);
                retVtr.push_back(strIP);
            }
            return;
        }
        
        if (curIdx == s.size() && curTry.size() < 4)
            return;
        
        int base = curIdx;
        int maxLen = _min(3, s.size()-curIdx); //这里要特别注意一个ip数字为 0-255最多三位
        for (int len=1; len<=maxLen; len++)
        {
            if (s[base] == '0' && len > 1)
                return; // 0 作为单独的数是可以的,但是不能作为多于一位的数的开始
            
            string curString = s.substr(base, len);
            long curNum = stoll(curString);
            
            if (isValidNum(curNum))
            {
                curTry.push_back((int)curNum);
                restoreIpAddressesHelper(s, curIdx+len, curTry, retVtr);
                curTry.pop_back();
            }
        }
    }
    
public:
    /**
     * @param s the IP string
     * @return All possible valid IP addresses
     */
    vector<string> restoreIpAddresses(string& s) {
        // Write your code here
        
        vector<string> retVtr;
        
        if (s.size() == 0)
            return retVtr;
            
        vector<int> curTry;
        
        restoreIpAddressesHelper(s, 0, curTry, retVtr);
        
        return retVtr;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值