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;
}
};