【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)


题意:给定一个字符串将它转换成ip地址;这个题目还是挺有意思的


方法一:暴力解决,将字符串切分成四段;

#include <iostream>
#include <stdio.h>
#include <vector>
#include <iterator>
#include <map>
using namespace std;

class Solution
{
public:
	vector<string> restoreIpAddresses(string s)
	{
		vector<string> val;
		int len = s.length();
		for (int i=1; i<=3; i++)
		{
			for (int j=1; j<=3; j++)
			{
				for (int k=1; k<=3; k++)
				{
					for (int m=1; m<=3; m++)
					{
						if (i+j+k+m==len)
						{
							string str1, str2, str3, str4;
							int tmp;
							str1 = s.substr(0, i); if (str1.length() > 1 && str1[0] == '0')continue;
							str2 = s.substr(i, j); if (str2.length() > 1 && str2[0] == '0')continue;
							str3 = s.substr(i+j, k); if (str3.length() > 1 && str3[0] == '0')continue;
							str4 = s.substr(i+j+k, m); if (str1.length() > 1 && str4[0] == '0')continue;

							tmp = atoi(str1.c_str());
							if (tmp > 255 || tmp < 0) continue;
							tmp = atoi(str2.c_str());
							if (tmp > 255 || tmp < 0) continue;
							tmp = atoi(str3.c_str());
							if (tmp > 255 || tmp < 0) continue;
							tmp = atoi(str4.c_str());
							if (tmp > 255 || tmp < 0) continue;

							val.push_back(str1+"."+str2+"."+str3+"."+str4);
						}
					}
				}
			}
		}

		return val;
	}

};



方法二:
用DFS的思想来做;

#include <iostream>
#include <stdio.h>
#include <vector>
#include <iterator>
#include <map>
using namespace std;

class Solution
{
public:
	vector<string> restoreIpAddresses(string s)
	{
		vector<string> ret;
		string t;
		DFS(ret, t, s, 0);
		return result;
	}
	void DFS(vector<string>& result, string t, string s, int count)
	{
		if (count==3 && isValid(s))
		{
			result.push_back(t+s);
			return;
		}

		for (int i=1; i<4 && i<s.size(); i++)
		{
			string sub = s.substr(0,i);
			if (isValid(sub))
			{
				DFS(result, t+sub+'.', s.substr(i), count+1);
			}
		}
	}

	bool isValid(string& s)
	{
		stringstream ss(s);
		int num;
		ss >> num;
		if (s.size()>1)
		{
			return s[0] != '0' && num>=0 && num<=255;
		}

		return num >= 0 && num <=255;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值