java 输入一个长度为 n 由大小写字母组成的字符串,打印出该字符串中字符的所有排列
时间: 2023-08-11 20:04:46 浏览: 178
您可以使用递归的方式来实现字符串中字符的所有排列。下面是一个示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String str = scanner.nextLine();
List<String> permutations = findPermutations(str);
System.out.println("字符串中字符的所有排列为:");
for (String permutation : permutations) {
System.out.println(permutation);
}
}
public static List<String> findPermutations(String str) {
List<String> permutations = new ArrayList<>();
if (str == null || str.length() == 0) {
return permutations;
}
char[] chars = str.toCharArray();
boolean[] visited = new boolean[chars.length];
StringBuilder sb = new StringBuilder();
backtrack(chars, visited, sb, permutations);
return permutations;
}
private static void backtrack(char[] chars, boolean[] visited, StringBuilder sb, List<String> permutations) {
if (sb.length() == chars.length) {
permutations.add(sb.toString());
return;
}
for (int i = 0; i < chars.length; i++) {
if (visited[i]) {
continue;
}
visited[i] = true;
sb.append(chars[i]);
backtrack(chars, visited, sb, permutations);
sb.deleteCharAt(sb.length() - 1);
visited[i] = false;
}
}
}
```
运行这段代码后,您可以输入一个长度为n的由大小写字母组成的字符串。程序将会打印出该字符串中字符的所有排列。
注意:该算法的时间复杂度为O(n!),当n较大时,可能会消耗较长的时间和内存。
阅读全文