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)
Have you been asked this question in an interview?
I made a ridiculous mistake in this problem. I once wrote the str2num function like:
bool str2num(const string& s, int start, int end) {
int num = 0;
if (s[start] == '0' && start != end)
return false;
while (start <= end) {
//num *= 10;
num += (s[start] - '0') + num*10;
//num = num + (s[start] - '0') + num*10;
++start;
}
if (num >= 0 && num <= 255)
return true;
return false;
}
This line seems right, however, this bug torments me all the afternoon. Pls remember, in such case num*=, +=, num never appears in the right side.
num += (s[start] - '0') + num*10;
The following is the right code :
class Solution {
public:
vector<string> res;
int str2num(const string& s, int start, int end) {
int num = 0;
while (start <= end) {
num += (s[start] - '0') + num *10;
++start;
}
return num;
}
void restore(const string& s, int start, int depth, vector<string>& cur_str) {
int num = 0;
string ip="";
int left = s.length() - start;
if (left < 4 - depth || left > (4 - depth) * 3)
return;
if (depth == 3 && s.length() - 3 <= start) {
num = str2num(s, start, s.length() - 1);
if (num >= 0 && num <= 255) {
for (int i = 0; i < cur_str.size(); ++i) {
ip += cur_str[i];
}
ip += s.substr(start, s.length() - start);
res.push_back(ip);
}
return;
}
else if(depth == 3 && s.length() - 3 > start){
return;
}
else {
for (int i = 0; i <= 2 && start + i < s.length(); i++ ) {
num = str2num(s, start, start + i);
if (num >= 0 && num <= 255) {
cur_str.push_back(s.substr(start, i+1));
cur_str.push_back(".");
restore(s, start + i +1, depth + 1, cur_str);
cur_str.pop_back();
cur_str.pop_back();
}
}
}
}
vector<string> restoreIpAddresses(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
res.clear();
vector<string> cur_str;
restore(s, 0, 0, cur_str);
return res;
}
};
Python Version:
class Solution:
def isValid(self, s):
cur_len = len(s)
if (s[0] == '0' and cur_len > 1):
return False
for ch in s:
if (ch < '0' or ch > '9'):
return False
num = int(s)
return num >= 0 and num <= 255
def restoreIpAddresses(self, s):
res = []
self.dfs(s, [], 4, res)
return res
def dfs(self, s, segs, depth, res):
if (depth == 1):
if (self.isValid(s)):
res.append(".".join(segs+[s]))
return
cur_len = len(s)
if (cur_len <= 0):
return
for i in range(1,4):
if (self.isValid(s[0:i]) and i+(depth-1)*1<=cur_len and i+(depth-1)*3>=cur_len):
self.dfs(s[i:], segs+[s[0:i]], depth-1, res)
s = Solution()
res = s.restoreIpAddresses("")
print(res)