首页 > 代码库 > [JAVA][ZOJ 1004][Anagrams by Stack]
[JAVA][ZOJ 1004][Anagrams by Stack]
[java] view plaincopyprint?
- import java.io.BufferedInputStream;
- import java.util.Scanner;
- public class Main {
- static String start;// record the first str
- static String end;// record the rearranged str
- public static void dfs(char[] stack, char[] sequence, int posInStart, int posInEnd, int posInStack) {
- if (posInStart + posInEnd == start.length() * 2) {// if all the letter has been rearranged
- for (int i = 0; i < sequence.length; i++) {
- System.out.print(sequence[i] + " ");// output the sequence
- }
- System.out.println();
- }
- if (posInStart < start.length()) {
- sequence[posInStart + posInEnd] = ‘i‘;
- stack[++posInStack] = start.charAt(posInStart);// push in
- dfs(stack, sequence, posInStart + 1, posInEnd, posInStack);
- posInStack--;// pop out
- }
- if (posInStack >= 0 && posInEnd < end.length() && stack[posInStack] == end.charAt(posInEnd)) {// pop out
- sequence[posInStart + posInEnd] = ‘o‘;
- posInStack--;// pop out
- dfs(stack, sequence, posInStart, posInEnd + 1, posInStack);
- stack[++posInStack] = end.charAt(posInEnd);
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(new BufferedInputStream(System.in));
- while (sc.hasNext()) {
- start = sc.next();
- end = sc.next();
- char[] stack = new char[start.length() * 2];// use array as the stack
- char[] sequence = new char[start.length() * 2];// record the operation seq, it will have (start.length() * 2) times operations
- System.out.println("[");
- dfs(stack, sequence, 0, 0, -1);
- System.out.println("]");
- }
- }
- }
最近写的几道题都用到了dfs,用数组代替栈的使用,控制好stack数字下标就没什么大问题,难得一次AC
[JAVA][ZOJ 1004][Anagrams by Stack]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。