Restore IP Addresses
30:00
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Given "25525511135"
, return
[
"255.255.11.135",
"255.255.111.35"
]
Order does not matter.
class Solution {
private:
int _min(int a, int b)
{
if (a <= b)
return a;
return b;
}
string getIP(vector<int> &curTry) {
string ret = "";
for (int i=0; i<4; i++)
{
ret = ret + to_string(curTry[i]);
if (i != 3)
ret = ret + ".";
}
return ret;
}
bool isValidNum(long num) {
if (num >= 0 && num <= 255) //0 也是可以的
return true;
return false;
}
void restoreIpAddressesHelper(string &s, int curIdx, vector<int> &curTry, vector<string> &retVtr)
{
if (curTry.size() == 4)
{
if (curIdx == s.size())
{
string strIP = getIP(curTry);
retVtr.push_back(strIP);
}
return;
}
if (curIdx == s.size() && curTry.size() < 4)
return;
int base = curIdx;
int maxLen = _min(3, s.size()-curIdx); //这里要特别注意一个ip数字为 0-255最多三位
for (int len=1; len<=maxLen; len++)
{
if (s[base] == '0' && len > 1)
return; // 0 作为单独的数是可以的,但是不能作为多于一位的数的开始
string curString = s.substr(base, len);
long curNum = stoll(curString);
if (isValidNum(curNum))
{
curTry.push_back((int)curNum);
restoreIpAddressesHelper(s, curIdx+len, curTry, retVtr);
curTry.pop_back();
}
}
}
public:
/**
* @param s the IP string
* @return All possible valid IP addresses
*/
vector<string> restoreIpAddresses(string& s) {
// Write your code here
vector<string> retVtr;
if (s.size() == 0)
return retVtr;
vector<int> curTry;
restoreIpAddressesHelper(s, 0, curTry, retVtr);
return retVtr;
}
};