leetcode 93. 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 {
	int my_atoi(string s)
	{
		int re = 0;
		int k = 0;
		while (k <s.length())
		{
			re = 10 * re + s[k] - '0';
			k++;
		}
		return re;
	}
public:
	vector<string> restoreIpAddresses(string s) {
		vector<string>re;
		vector< string>candi; vector<string>aa;
		candi.push_back(s);
		int k = 0;
		while (true)
		{
			vector<string>newcandi;
			k++;
			for (int i = 0; i < candi.size(); i++)
			{
				if (k == 1)
				{
					for (int j = 1; j <= 3; j++)
					{
						string ss = candi[i];
						if (ss.length() - j >= 3 && ss.length() - j <= 9)
						{
							int n = my_atoi(string(ss.begin(), ss.begin() + j));
							if ( n <= 255)
							{
								if ((n == 0 && j == 1)||(n>0&&ss[0]!='0'))
								{
									ss.insert(ss.begin() + j, '.');
									newcandi.push_back(ss);
								}

							}
						}
					}
				}
				else if (k == 2)
				{
					for (int j = 1; j <= 3; j++)
					{
						string ss = candi[i];
						int pos = ss.rfind('.');
						if (ss.length() - j-pos-1 >= 2 && ss.length() - j -pos-1<= 6)
						{
							int n = my_atoi(string(ss.begin() + pos + 1, ss.begin() + pos + 1 + j));
							if (n <= 255 )
							{
								if ((n == 0 && j == 1) || (n > 0 && ss[pos + 1] != '0'))
								{
									ss.insert(ss.begin() + pos + j + 1, '.');
									newcandi.push_back(ss);
								}
							}
						}
					}
				}
				else if (k == 3)
				{
					for (int j = 1; j <= 3; j++)
					{
						string ss = candi[i];
						int pos = ss.rfind('.');
						if (ss.length() - j -pos-1>= 1 && ss.length() - j-pos-1 <= 3)
						{
							int n = my_atoi(string(ss.begin() + pos + 1, ss.begin() + pos + 1 + j));
							int n2 = my_atoi(string(ss.begin() + 1 + j + pos, ss.end()));
							if (n <= 255 && n2 <= 255)
							{
								if (((n == 0 && j == 1) || (n > 0 && ss[pos + 1] != '0')) &&
									((n2 == 0 && 1 + j + pos == ss.length() - 1) || (n2>0 && ss[1 + j + pos] != '0')))
								{
									ss.insert(ss.begin() + pos + j + 1, '.');
									re.push_back(ss);
								}
							}
						}
					}
					
				}
			}
			candi = newcandi;
			if (k == 3)
				return re;
		}
	}
};

accepted


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值