我已经编写了以下for循环来显示所提供单词的所有子字符串。然而,其中一个要求是将该单词仅显示为一个唯一的子串。如果'mom'给出了以下代码,它将长度为1的子串显示为'm','o'和'm',给出'm'的副本。您如何确保只打印出唯一的子串?
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);
}
}
}
答案 0 :(得分:1)
使用套装记住您已经看过的内容。对于任何长度为n的字符串,您有大约(n ^ 2)/ 2个子字符串,因此Set的大小将受此限制。
答案 1 :(得分:1)
尝试以下代码。它应该按照你的要求工作。
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
final public class Main
{
public static void main(String...args)
{
String string, sub;
ArrayList<String>al=new ArrayList<String>();
int i, c, length;
Scanner in = new Scanner(System.in);
System.out.print("Enter a string to print it's all unique substrings:->");
string = in.nextLine();
length = string.length();
System.out.print("Substrings of \""+string+"\" are :->");
for(c=0;c<length;c++)
{
for(i=1;i<=length-c;i++)
{
sub = string.substring(c,c+i);
al.add(sub);
}
}
HashSet hs = new HashSet();
hs.addAll(al);
al.clear();
al.addAll(hs);
for(String str:al)
{
System.out.println(str);
}
}
}
删除重复元素的最简单方法是将内容添加到Set
,这不允许重复,然后将Set添加回ArrayList
答案 2 :(得分:0)
我们可以直接这样做而不使用arraylist它会使你接受的上述答案有点令人困惑。检查我的代码。
public class Subst {
public static void main(String args[]) {
String st;
HashSet<String> hs = new HashSet<String>();
Scanner in = new Scanner(System.in);
st = in.nextLine();
int length = st.length();
for (int i = 0; i < length; i++) {
for (int j = i + 1; j <= length; j++) {
hs.add(st.substring(i, j));
}
}
System.out.println(hs);
}
}