logo CodeStepByStep logo

validIpAddresses

Language/Type: Java recursion backtracking
Related Links:

Write a recursive method named validIpAddresses that accepts a string s consisting only of digit characters and prints all possible valid internet protocol (IP) addresses that could be made from those characters. A valid IP address contains four numbers between 0 and 255 inclusive separated by period (.) characters. For example, the call of validIpAddresses("25511134255"); should print the following console output:

255.11.134.255
255.111.34.255

Note that exactly three dots must be placed between four numeric values and that those values must be between 0 and 255 inclusive. A string that violates either of these constraints is not a valid IP address. Also note that each line of output must contain every character from s in the same relative order. The number 0 is somewhat a special case; the four numbers in an IP address cannot have leading zeros. So, for example, the string of 123.45.01.78 is not a valid IP address, but 123.45.0.178 would be. Similarly, 123.45.00.178 would be invalid because of the double 0 in the third numeric component.

You can print the lines of output in any order. If there are no valid IP addresses that can be made using the given string, print no output. You may assume that the string passed will contain only digit characters from 0-9.

Constraints: Do not declare any global variables. You can use any data structures you like, and your code can contain loops, but the overall algorithm must be recursive and must use backtracking. You are allowed to define other "helper" methods if you like; they are subject to these same constraints.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.