Unique Substring Count
This program counts unique substrings in a string.
Problem Statement
Write a Java program to count unique substrings in "aba".
Source Code
| 1 | import java.util.HashSet; |
| 2 | public class UniqueSubstringCount { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Unique Substring Count"); |
| 5 | String str="aba"; |
| 6 | HashSet<String> set=new HashSet<>(); |
| 7 | for(int i=0;i<str.length();i++){ |
| 8 | for(int j=i+1;j<=str.length();j++){ |
| 9 | set.add(str.substring(i,j)); |
| 10 | } |
| 11 | } |
| 12 | System.out.println("Unique substrings count = "+set.size()); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Unique Substring Count Unique substrings count = 5
Explanation
Nested loops generate every possible substring of the string, and a HashSet automatically discards duplicates, so its final size gives the count of unique substrings.