给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。
样例:
给出字符串 “25525511135”,所有可能的IP地址为:
[
"255.255.11.135",
"255.255.111.35"
]
(顺序无关紧要)
#ifndef C426_H
#define C426_H
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
/*
* @param s: the IP string
* @return: All possible valid IP addresses
*/
vector<string> restoreIpAddresses(string &s) {
// write your code here
vector<string> res;
if (s.empty() || s.size() > 12)
return res;
int len = s.size();
for (int i = 1; i <= 3; ++i)
{
for (int j = 1; j <= 3; ++j)
{
for (int k = 1; k <= 3; ++k)
{
string str = s;
if (i + j + k < len&&isValid(i,j,k,str))
{
str.insert(i, ".");
str.insert(i + j + 1, ".");
str.insert(i + j + k + 2, ".");
res.push_back(str);
}
}
}
}
return res;
}
bool isValid(int i, int j, int k, string str)
{
int len = str.size();
string si = str.substr(0, i);
string sj = str.substr(i,j);
string sk = str.substr(i + j, k);
string sd = str.substr(i + j + k, len - i - j - k);
if (stoi(si) <= 255 && stoi(sj) <= 255 && stoi(sk) <= 255 && stoi(sd) <= 255)
{
if ((si[0] == '0'&&i > 1) || (sj[0] == '0'&&j > 1) || (sk[0] == '0'&&k > 1) || (sd[0] == '0'&&len - i - j - k > 1))
return false;
else
return true;
}
else
return false;
}
};
#endif