Given a string s
containing only digits, return all possible valid IP addresses that can be obtained from s
. You can return them in any order.
A valid IP address consists of exactly four integers, each integer is between 0
and 255
, separated by single dots and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "[email protected]" are invalid IP addresses.
Example 1:
Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000" Output: ["0.0.0.0"]
Example 3:
Input: s = "1111" Output: ["1.1.1.1"]
Example 4:
Input: s = "010010" Output: ["0.10.0.10","0.100.1.0"]
Example 5:
Input: s = "101023" Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Constraints:
0 <= s.length <= 3000
s
consists of digits only.
DFS.
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
ans = []
def check(s):
if not (0 <= int(s) <= 255):
return False
if s[0] == '0' and len(s) > 1:
return False
return True
def dfs(s, t):
if len(t) == 4:
if not s:
ans.append('.'.join(t))
return
for i in range(1, min(4, len(s) + 1)):
if check(s[:i]):
t.append(s[:i])
dfs(s[i:], t)
t.pop()
dfs(s, [])
return ans
class Solution {
private List<String> ans;
public List<String> restoreIpAddresses(String s) {
ans = new ArrayList<>();
dfs(s, new ArrayList<>());
return ans;
}
private void dfs(String s, List<String> t) {
if (t.size() == 4) {
if ("".equals(s)) {
ans.add(String.join(".", t));
}
return;
}
for (int i = 1; i < Math.min(4, s.length() + 1); ++i) {
String c = s.substring(0, i);
if (check(c)) {
t.add(c);
dfs(s.substring(i), t);
t.remove(t.size() - 1);
}
}
}
private boolean check(String s) {
if ("".equals(s)) {
return false;
}
int num = Integer.parseInt(s);
if (num > 255) {
return false;
}
if (s.charAt(0) == '0' && s.length() > 1) {
return false;
}
return true;
}
}
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
vector<string> t;
dfs(s, t, ans);
return ans;
}
void dfs(string s, vector<string>& t, vector<string>& ans) {
if (t.size() == 4)
{
if (s == "")
{
string p = "";
for (auto e : t) p += e + ".";
p.pop_back();
ans.push_back(p);
}
return;
}
for (int i = 1; i < min(4, (int) s.size() + 1); ++i)
{
string c = s.substr(0, i);
if (check(c))
{
t.push_back(c);
dfs(s.substr(i, s.size() - i), t, ans);
t.pop_back();
}
}
}
bool check(string s) {
if (s == "") return false;
int num = stoi(s);
if (num > 255) return false;
if (s[0] == '0' && s.size() > 1) return false;
return true;
}
};