📅  最后修改于: 2023-12-03 15:02:06.093000             🧑  作者: Mango
在Java中,可以通过递归方法来打印字符串的不同排列。下面的代码片段演示了如何实现这个功能。
import java.util.HashSet;
import java.util.Set;
public class StringPermutation {
public static Set<String> permutationFinder(String str) {
Set<String> perm = new HashSet<String>();
if (str == null || str.length() == 0) {
perm.add("");
return perm;
}
char initial = str.charAt(0);
String rem = str.substring(1);
Set<String> words = permutationFinder(rem);
for (String strNew : words) {
for (int i = 0;i<=strNew.length();i++){
perm.add(charInsert(strNew, initial, i));
}
}
return perm;
}
public static String charInsert(String str, char c, int j) {
String begin = str.substring(0, j);
String end = str.substring(j);
return begin + c + end;
}
public static void main(String[] args) {
String s = "java";
Set<String> pset = permutationFinder(s);
System.out.println(pset);
}
}
permutationFinder
方法来获取输入字符串的所有排列。permutationFinder
方法,将其余字符串作为参数传递给它。这将返回一个Set,其中包含其余字符串的所有排列。以上代码演示了如何使用递归方法来打印字符串的不同排列。通过这种方法,我们可以轻松地获取字符串的所有排列。