leetcode 93. 复原ip地址

题意就是给你一串数字 在里面加小数点 能恢复成正确的ip地址
要注意001 ,020 这样在数字前面出现0的ip地址是不合法的
就是简单的递归 代码如下

vector<string> ret;
string temp;
int n;
void dfs(string &s,int depth,int cur_index)
{
	if (depth == 4)
	{
		if (cur_index == n)
		{
			temp.pop_back();
			ret.push_back(temp);
			temp.push_back('.');
		}
		return;
	}
	int cur = 0;
	int i;
	for (i = 0; i < min(3,n-cur_index); i++)
	{
		cur = cur * 10 + (s[cur_index + i] - '0');
		if (cur > 255) break;
		temp.push_back(s[cur_index + i]);
		temp.push_back('.');
		dfs(s, depth + 1, cur_index + i + 1);
		temp.pop_back();
		if (cur == 0)
		{
			temp.pop_back();
			break;
		}
	}
	while (i--) temp.pop_back();
}

vector<string> restoreIpAddresses(string s) {
	temp.clear();
	ret.clear();
	n = s.size();
	dfs(s, 0, 0);
	return ret;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值