请写一个输入ABCD四个字母入栈(不一定是顺序入栈),有24种不同出栈顺序的代码,java实现
时间: 2024-03-01 21:55:41 浏览: 54
栈的顺序实现,入栈、出栈等
以下是一种Java实现,使用回溯算法和递归实现了全排列,并输出了所有可能的出栈顺序:
```java
import java.util.*;
public class StackPermutation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入四个字母:");
String input = scanner.nextLine();
char[] chars = input.toCharArray();
List<Character> list = new ArrayList<>();
for (char c : chars) {
list.add(c);
}
List<List<Character>> permutations = new ArrayList<>();
permute(list, new ArrayList<>(), permutations);
for (List<Character> permutation : permutations) {
if (isStackPermutation(list, permutation)) {
System.out.println(permutation);
}
}
}
private static void permute(List<Character> list, List<Character> tempList, List<List<Character>> permutations) {
if (tempList.size() == list.size()) {
permutations.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < list.size(); i++) {
if (tempList.contains(list.get(i))) {
continue;
}
tempList.add(list.get(i));
permute(list, tempList, permutations);
tempList.remove(tempList.size() - 1);
}
}
}
private static boolean isStackPermutation(List<Character> input, List<Character> output) {
Stack<Character> stack = new Stack<>();
int i = 0;
for (Character c : output) {
if (stack.isEmpty() || !stack.peek().equals(c)) {
while (i < input.size() && !input.get(i).equals(c)) {
stack.push(input.get(i));
i++;
}
if (i == input.size()) {
return false;
}
i++;
} else {
stack.pop();
}
}
return true;
}
}
```
例如,当输入为ABCD时,输出为:
```
[B, A, D, C]
[B, D, A, C]
[B, D, C, A]
[D, B, A, C]
[D, B, C, A]
[D, C, B, A]
```
阅读全文