I am trying to find all possible distinct substrings of a string. This is my current code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
StringBuffer f = new StringBuffer();
//Get a string of possible substrings with out uniqueness
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
f.append(str.charAt(j) + ",");
}
}
f.deleteCharAt(sb.length() - 1);
String s = f.toString();
String[] arr = s.Split(',');
arr = arr.Distinct().ToArray();
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
I received multiple errors when compiling. I do not understand where the code went wrong. Did I forgot to import a class or do I have a syntax error?
Solution.java:28: error: cannot find symbol
f.deleteCharAt(sb.length()-1);
^
symbol: variable sb
location: class Solution
Solution.java:31: error: cannot find symbol
String[] arr = s.Split(',');
^
symbol: method Split(char)
location: variable s of type String
Solution.java:34: error: cannot find symbol
arr = arr.Distinct().ToArray();
^
symbol: method Distinct()
location: variable arr of type String[]
3 errors
It's difficult to understand what you're intending to do, but when you say distinct substrings of a given string I don't think you mean unique letters. So have a look at this...
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length() + 1; j++) {
String substring = str.substring(i, j);
if (str.indexOf(substring, i + substring.length()) == -1) {
System.out.println("Unique Substring: " + substring);
}
}
}
}
I tested this with "hello", given your comment to the last answer. You'll notice that the first "l" (lower case L) is not part of the result because of the next "l" (lower case L), but the second "l" (lower case L) is a unique substring.
Is this what you're looking for?