查找字符串的所有不同子字符串 [英] finding all distinct substring of a string
问题描述
大家好,我遇到了作业问题,它要求我查找字符串的所有不同子字符串.我已经实现了一种方法,该方法将告诉您字符串的所有子字符串,但是我需要一个帮助来弄清楚如何不将已经被算作子字符串的一个算在内,因为分配是要找到不同的子字符串.
hello guys i was given homework problem where it asks me to find all distinct substring of a string. I have implemented a method which will tell you all the substrings of string but i need a help figuring out how to not count one which is already counted once as substring because assignment is to find distinct one.
public int printSubstrings1(int length)
{
for(int i=0; i<text.length()-length+1;i++)
{
String sub = text.substring(i,length+i);
counter++;
}
return counter;
}
在这里,我从给定的字符串中传递我想要的子字符串的长度.我正在通过另一种方法做到这一点.
here i am passing the length of substrings that i want from te string given. i am doing that through another method.
因此给定的示例字符串比单独的子字符串"fred"为10.由于该字符串不包含任何重复的字母,因此我的方法将输出正确答案.我被困在我确实得到重复的子字符串的部分.
so example string given is "fred" than the distinct substrings will be 10. my method will output right answer since the string does not contain any repeated letters. i am stuck on the part where i do get repeated substrings.
如果我输入弗雷德.这是我的方法将输出的内容
if i input fred. this is what my method will output
长度1
f
r
e
d
长度2
fr
重新
ed
长度3
fre
红色
长度4
弗雷德
length 1
f
r
e
d
length 2
fr
re
ed
length 3
fre
red
length 4
fred
推荐答案
public ArrayList<String> getAllUniqueSubset(String str) {
ArrayList<String> set = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < str.length() - i; j++) {
String elem = str.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
这篇关于查找字符串的所有不同子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!