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;
}
发布了9 篇原创文章 · 获赞 1 · 访问量 580

猜你喜欢

转载自blog.csdn.net/weixin_43149897/article/details/104101322