我有以下代码:
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));
}
}
}
}
当我运行此代码时,我得到以下输出:
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
哪个好而且全部 - 但它实际上并不是我想要的。我还希望能够获得所有可能的字符串作为这个词的子串。
如要点,集合,领带等。
我意识到我的代码是如何错误的,但我也不确定如何扩展它以实现我想要的目标!
感谢任何帮助!
答案 0 :(得分:0)
试试这个:效率不高,但似乎有效
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class MainClass {
private static Set<String> store = new HashSet<String>();
public static void main(String args[]) {
doAll("testi");
Iterator<String> it = store.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
public static void doAll(String str) {
for (int i = 0; i < str.length(); i++) {
String doingString = str.substring(i, str.length());
permuteString("", doingString);
}
}
public static void permuteString(String beginningString, String endingString) {
if (endingString.length() <= 1) {
store.add(beginningString + endingString);
doAll(beginningString);
}
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i)
+ endingString.substring(i + 1);
permuteString(beginningString + endingString.charAt(i),
newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
答案 1 :(得分:0)
您需要所有字符子集的所有排列。
使用番石榴:
Set<Character> chars = Sets.newHashSet(Chars.asList(source.toCharArray()));
Set<String> r = Sets.powerSet(chars).stream()
.flatMap(cs -> Collections2.permutations(cs).stream()
.map(l -> String.valueOf(Chars.toArray(l))))
.collect(Collectors.toSet());
答案 2 :(得分:0)
具有此排列功能(取自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;
}
这个子串函数(只是更改了函数的返回类型):
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流制作了这个解决方案:
public static void main(String[] args) {
Stream.of("Testing")
.flatMap(s -> permutation(s).stream())
.flatMap(s -> substrings(s).stream())
.distinct()
.forEach(System.out::println);
}