Program to generate all possible valid IP addresses from given string - GeeksforGeeks (2024)

// Java Program to generate all possible

// valid IP addresses from given string

import java.util.*;

class GFG

{

public static ArrayList<String> list;

// Function to restore Ip Addresses

public static ArrayList<String>

restoreIpAddresses(String s)

{

int n = s.length();

list = new ArrayList<>();

if (n < 4 || n > 12)

return list;

// initialize the dp array

int dp[][] = new int[4][n];

for (int i = 0; i < 4; i++)

{

for (int j = n - 1; j >= 0; j--)

{

if (i == 0)

{

// take the substring

String sub = s.substring(j);

if (isValid(sub))

{

dp[i][j] = 1;

}

else if (j < n - 3)

{

break;

}

}

else

{

if (j <= n - i)

{

for (int k = 1;

k <= 3 && j + k <= n;

k++)

{

String temp

= s.substring(j, j + k);

if (isValid(temp))

{

if (j + k < n

&& dp[i - 1][j + k]

== 1)

{

dp[i][j] = 1;

break;

}

}

}

}

}

}

}

if (dp[3][0] == 0)

return list;

// Call function createIpfromDp

createIpFromDp(dp, 3, 0, s, "");

return list;

}

public static void createIpFromDp(int dp[][],

int r,

int c, String s,

String ans)

{

if (r == 0)

{

ans += s.substring(c);

list.add(ans);

return;

}

for (int i = 1;

i <= 3 && c + i < s.length();

i++)

{

if (isValid(s.substring(c, c + i))

&& dp[r - 1] == 1)

{

createIpFromDp(dp, r - 1, c + i, s,

ans +

s.substring(c, c + i)

+ ".");

}

}

}

private static boolean isValid(String ip)

{

String a[] = ip.split("[.]");

for (String s : a)

{

int i = Integer.parseInt(s);

if (s.length() > 3 || i < 0 || i > 255)

{

return false;

}

if (s.length() > 1 && i == 0)

return false;

if (s.length() > 1 && i != 0

&& s.charAt(0) == '0')

return false;

}

return true;

}

// Driver Code

public static void main(String[] args)

{

// Function call

System.out.println(

restoreIpAddresses("25525511135").toString());

}

}

// This code is contributed by Nidhi Hooda.

I am an expert in Java programming and algorithmic problem-solving, with a deep understanding of data structures and dynamic programming. My expertise is grounded in practical application, and I have a demonstrable track record of solving complex problems efficiently. Now, let's delve into the provided Java code and discuss the concepts involved.

The given Java program is designed to generate all possible valid IP addresses from a given string. Here's an explanation of the key concepts used in the code:

  1. ArrayList:

    • The code uses the ArrayList<String> class to store the generated IP addresses. list is a static variable of type ArrayList<String>.
  2. Dynamic Programming (DP):

    • Dynamic programming is employed to optimize the solution. The dp array is a 2D array (int[4][n]), where n is the length of the input string. It is used to store intermediate results during the process of generating IP addresses.
  3. isValid Function:

    • The isValid function checks whether a given substring is a valid part of an IP address. It ensures that the substring represents a number between 0 and 255 and handles cases where the substring has leading zeros.
  4. restoreIpAddresses Function:

    • This function is the main driver for generating valid IP addresses. It initializes the dp array and iterates through the input string to populate the array based on valid substrings. It then calls the createIpFromDp function to generate IP addresses.
  5. createIpFromDp Function:

    • This recursive function utilizes the information stored in the dp array to construct valid IP addresses. It backtracks through the DP array to form combinations of valid substrings.
  6. Splitting String and Integer Parsing:

    • The isValid function splits the input IP address string into segments using the split("[.]") method. Additionally, integer parsing is done using Integer.parseInt() to check if the segments are valid integers.
  7. Main Method:

    • The main method serves as the entry point. It calls the restoreIpAddresses function with a sample input ("25525511135") and prints the generated IP addresses.

This code efficiently uses dynamic programming to avoid redundant calculations while exploring all possible combinations of valid IP addresses. The modular design makes it easy to understand and maintain. If you have any specific questions or if there's a particular aspect you'd like more information on, feel free to ask.

Program to generate all possible valid IP addresses from given string - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 5578

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.