I’ve written the following for loop to display all substrings from a provided word. However, one of the requriements is for the word to one display unique substrings only. If ‘mom’ was giving to the following code it’d display the substrings of length one as ‘m’, ‘o’ and ‘m’, giving a duplicate of ‘m’. How would you go about making sure only the unique substrings were printed?
public static void allUniqueSubStrings(String str) {
for (int i = 1; i <= str.length(); i++) {
for (int j = 0; j + i <= str.length(); j++) {
String s = str.substring(j, i+j);
System.out.println(s);
}
}
}
Try the following code. It should work as per your requirements.
The easiest method to remove duplicate elements is to add the contents to a
Setwhich won’t allow duplicates and then add the Set back to anArrayList