Monday, May 2, 2022

Question 7 : Find all substrings of String in java?

Solution: Java program to find all substrings of a String.

For example: If the input is “abb”  then the output should be “a”, “b”,”b”, “ab”, “bb”, “abb”
We will use the String class’s subString method to find all substrings.

We will use the String class’s subString method to find all subString

Program::

public class SubstringsOfStringMain { public static void main(String args[]) { String str="abbc"; System.out.println("All substring of abbc are:"); for (int i = 0; i < str.length(); i++) { for (int j = i+1; j <= str.length(); j++) { System.out.println(str.substring(i,j)); } }

  Set<String> substrings = new HashSet<>();
  generateSubstrings(str, 0, "", substrings);

  // Print unique substrings
  for (String substring : substrings) {
            System.out.println(substring);
  }
}

static void generateSubstrings(String str, int index, String current, Set<String> substrings) {
        if (index == str.length()) {
            substrings.add(current); // Add the current substring
            return;
        }

        // Include the current character
        generateSubstrings(str, index + 1, current +                       str.charAt(index), substrings);

        // Exclude the current character
        generateSubstrings(str, index + 1, current, substrings);
    }
}


When you run the above program, you will get the following output:
All substring of abbc are: a ab abb abbc b bb bbc b bc c The above solution is of o(n^3) time complexity. As we have two loops and also String’s substring method has a time complexity of o(n). If you want to find all distinct substrings of String, then use HashSet to remove duplicates.


Don't miss the next article!

Be the first to be notified when a new article or Kubernetes experiment is published.                            

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS