LEETCODE: 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)



忍不住又做了一题!


class Solution {
public:
    void getAddresses(vector<string> &results, string s, string temp, int segment) {
        if(s.length() < segment) return;
        if(segment == 1) {
            if(s.length() >= 2 && s[0] == '0') return;
            if(s.length() < 3 || (s.length() == 3 && s <= "255"))
                results.push_back(temp + "." + s); 
            return;
        }
        
        string s0(s, 0, 1);
        if(s.length() - 1 <= (segment - 1) * 3) {
            string newstr = temp + (segment == 4 ? "" : ".");
            newstr += s0;
            getAddresses(results, s.substr(1, s.length() - 1), newstr, segment - 1);
        }
        
		if(s[0] == '0')
			return;

        string s1(s, 0, 2);
        if(s.length() - 2 <= (segment - 1) * 3) {
            string newstr = temp + (segment == 4 ? "" : ".");
            newstr += s1;
            getAddresses(results, s.substr(2, s.length() - 2), newstr, segment - 1);
        }
        
		if(s[0] == '0' && s[1] == '0')
			return;
        string s2(s, 0, 3);
        if(s.length() - 3 <= (segment - 1) * 3 && s2 <= "255") {
            string newstr = temp + (segment == 4 ? "" : ".");
            newstr += s2;
            getAddresses(results, s.substr(3, s.length() - 3), newstr, segment - 1);
        }
    }
    vector<string> restoreIpAddresses(string s) {
        if(s.length() < 3 || s.length() > 12) return vector<string>();
        vector<string> results;
        string temp;
        getAddresses(results, s, temp, 4);
        return results;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值