我如何获得不仅仅是所有子串,而是一个字符串的所有可能的子串? [英] How do I get not just all substrings, but all POSSIBLE substrings of a string?
问题描述
我有以下代码:
public class Application {
public static void main(String[] args)
{
String source = "Testing";
go(source);
}
public static void go(String source)
{
for (int i = 0; i < source.length(); i ++)
{
for (int j = i + 1; j <= source.length(); j++)
{
System.out.println(source.substring(i, j));
}
}
}
}
当我运行此代码时,我得到以下输出:
When I run this code, I get the following output :
T
Te
Tes
Test
Testi
Testin
Testing
e
es
est
esti
estin
esting
s
st
sti
stin
sting
t
ti
tin
ting
i
in
ing
n
ng
g
哪个好而且全部 - 但实际上并不是我想要的。我还希望能够获得所有可能的字符串,这些字符串是这个词的子串。
Which is great and all - But it isn't actually what I want. I would also like to be able to get all the possible strings that are substrings of this word.
如gist,set,tie等。
Such as gist, set, tie etc.
我意识到我的代码是如何错误的,但我也不确定如何扩展它以实现我想要的目标!
I realise how my code is wrong for this, but I am also unsure of how I might expand it out to achieve what I want!
感谢任何帮助!
推荐答案
通过具有此排列功能(取自生成给定字符串的所有排列):
By having this permutations function (taken from Generating all permutations of a given string):
public static List<String> permutation(final String str) {
return permutation("", str);
}
private static List<String> permutation(final String prefix, final String str) {
final List<String> list = new ArrayList<>();
final int n = str.length();
if (n == 0) {
list.add(prefix);
} else {
for (int i = 0; i < n; i++) {
list.addAll(permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, n)));
}
}
return list;
}
这个子串函数(只是更改了函数的返回类型):
And this substring function (just changed the return type of your function):
public static List<String> substrings(final String source) {
final List<String> list = new ArrayList<>();
for (int i = 0; i < source.length(); i++) {
for (int j = i + 1; j <= source.length(); j++) {
list.add(source.substring(i, j));
}
}
return list;
}
我使用Java 8流制作了这个解决方案:
I made this solution using Java 8 streams:
public static void main(String[] args) {
Stream.of("Testing")
.flatMap(s -> permutation(s).stream())
.flatMap(s -> substrings(s).stream())
.distinct()
.forEach(System.out::println);
}
这篇关于我如何获得不仅仅是所有子串,而是一个字符串的所有可能的子串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!