Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given
Given
"25525511135",
return
Understand the problem:["255.255.11.135", "255.255.111.35"]. (Order does not matter)The problem gives a string containing only digits, restore by returning all possible valid IP addresses combinations.
So the crux of the problem is to understand "what is a valid IP address"? A valid IP address has the format of xxx.xxx.xxx.xxx, where xxx is a number from 0 to 255. Note that there are some reserved IP addresses, but this problem only asks for the valid structure of the IP addresses. Therefore a valid IP address could range from 0.0.0.0 to 255.255.255.255.
Recursive Solution:
This is another permutation and combination problem.
Code (Java):
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<String>();
if (s == null || s.length() < 4) {
return result;
}
restoreHelper(s, 0, 1, "", result);
return result;
}
private void restoreHelper(String s, int start, int segment, String curr, List<String> result) {
if (start >= s.length()) {
return;
}
if (segment == 4) {
if (isValid(s.substring(start))) {
result.add(curr + "." + s.substring(start));
}
return;
}
for (int i = 1; i < 4 && start + i < s.length(); i++) {
String temp = s.substring(start, start + i);
if (isValid(temp)) {
if (segment == 1) {
restoreHelper(s, start + i, segment + 1, temp, result);
} else {
restoreHelper(s, start + i, segment + 1, curr + "." + temp, result);
}
}
}
}
private boolean isValid(String str) {
if (str == null || str.length() > 3) {
return false;
}
int num = Integer.parseInt(str);
if (str.charAt(0) == '0' && str.length() > 1) {
return false;
}
if (num >= 0 && num <= 255) {
return true;
}
return false;
}
}
No comments:
Post a Comment