我试图找到一个字符串的所有可能的不同子字符串。这是我当前的代码:
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]);
}
}
编译时收到多个错误。我不明白代码哪里出了问题。我是否忘记了导入类或语法错误?
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
最佳答案
很难理解您要执行的操作,但是当您说给定字符串的不同子字符串时,我认为您的意思不是唯一的字母。所以看看这个...
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);
}
}
}
}
考虑到您对最后一个答案的评论,我使用“你好”进行了测试。您会注意到,由于下一个“l”(小写字母L),第一个“l”(小写字母L)不是结果的一部分,但是第二个“l”(小写字母L)是唯一的子字符串。
这是您要找的东西吗?
关于java - 给定字符串的不同子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30264651/