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)

好多特殊情况:

递归到最后一个数是9245587303,stoi越界

多个零:10.000.0.1

数字前面是以0开始:10.010.0.1

vector<string> restore(string s, int n, bool &flag)
	{
		vector<string> res;
		if(s.length() < n) {flag = false; return res;}
		if(n==1)
		{
			if(s.length()>3){flag=false;return res;}//maybe larger than int
			int ip = stoi(s);
			if(ip==0 && s.length() >1) flag = false;
			else if(ip>0 && s[0] == '0') flag = false;
			else if((ip >= 0) && (ip < 256))
			{
				res.push_back(s);
				flag = true;
			}else
				flag = false;
			return res;
		}
		int loop = s.length() - n +1;//garuntee every ip address is no less than one bit
		loop = min(loop,3);
		for(int i = 1; i <= loop; i++)
		{
			string ipstr = s.substr(0,i);
			int ip = stoi(ipstr);
			if(ip==0 && ipstr.length() >1)break;
			if(ip>0 && ipstr[0] == '0')break;
			if((ip>=0) && (ip < 256))
			{
				string suffix = s.substr(i);
				bool f = false;
				vector<string> tmp = restore(suffix,n-1,f);
				if(f)
				{
					flag = true;
					for(int k = 0; k < tmp.size(); k++)
						res.push_back(ipstr + '.' + tmp[k]);
				}
			}
		}
		return res;
	}
	vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		vector<string> res;
		bool flag = false;
		res = restore(s,4,flag);
		return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值