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


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)); } } } }

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 AWS Java Coding Question
Microservices Core Java Python
Spring Framework AI/MLSpring Boot