How to find subsets of a given string

This is the first solution to list all the subsets or substrings of a given string. This uses the String’s class substring method for intermediate processing of all sized sub strings.

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class SubsetsOfString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Set<String> finalSubsetStrs = new HashSet<String>  ();
		Scanner inpStr=new Scanner (System.in);
		System.out.println("Enter an input word for which you need all the sub sets of strings");
		String inpWord=inpStr.next();
		int sizeOfSubstr=1,beginIdx=0, endIdx=1;
		
		//Iterate the loop until the substring's length is equals with length of the actual string
		while (sizeOfSubstr <= inpWord.length()) {
		
			//Iterate the substring sized loop until the subscript less than or equals the actual length
			while (beginIdx < inpWord.length() && endIdx <= inpWord.length()) 
				finalSubsetStrs.add(inpWord.substring(beginIdx++, endIdx++));
		
		sizeOfSubstr++; // Increment size of sub string for the next iteration
		beginIdx=0;
		endIdx=sizeOfSubstr;
		}
		System.out.println("All the unique substrings from the given String="+inpWord+" are below");
		System.out.println(finalSubsetStrs);
		inpStr.close();
	}
}
Output:
Enter an input word for which you need all the sub sets of strings
DAVE
All the unique substrings from the given String=DAVE are below
[AVE, A, DAVE, D, E, AV, V, DAV, DA, VE]


Comments

Leave a comment