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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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