给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: “25525511135”
输出: [“255.255.11.135”, “255.255.111.35”]
class Solution {
private:
bool isValidIp(string &strTemp)
{
if(strTemp.length() == 0 || (strTemp.length() > 1 && strTemp[0] == '0')) return false; //注意IP没有“01”这种的
int num = atoi(strTemp.c_str());
return (num >= 0 && num <= 255);
}
void dfs(vector<string> &vecRes, string &s, string strTemp, int left, int depth)
{
for(int right = left; right < s.length() && right <= left+2; right++) //注意此处的循环条件right <= left+2
{
if(s.length()-right-1 > (4-depth)*3) continue; //注意此处是s.length()-right-1,表示是该字符后面的字符
if(s.length()-right-1 < 4-depth) continue;
string strRes(s, left, right-left+1); //初始化截取字符串
if(isValidIp(strRes))
{
if(depth == 4)
{
strTemp += strRes;
vecRes.push_back(strTemp);
return;
}
dfs(vecRes, s, strTemp+strRes+'.', right+1, depth+1);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> vecRes;
if(s.length() > 12) return vecRes;
dfs(vecRes, s, "", 0, 1); //此处递归的深度从1开始
return vecRes;
}
};