ZOJ Problem Set - 1004 - Anagrams by Stack

import java.util.Scanner;

public class Main {
    private static char[] solution = new char[200];
    private static char[] s = new char[200];
    private static String source;
    private static String target;
    private static int top;
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while(input.hasNext()) {
            top = 1;
            source = input.nextLine();
            target = input.nextLine();
            if(source.length() != target.length()) {
                System.out.println("[\n]");
                continue;
            }
            System.out.println("[");
            dfs(0, 0, 0);
            System.out.println("]");
        }
    }

    private static void dfs(int depth, int npush, int npop) {
        if(source.length() == npush && npush == npop) {
            for(int i = 0; i < 2*source.length(); i++) {
                if(i == 2*source.length()-1) {
                    System.out.println(solution[i] + " ");
                } else {
                    System.out.print(solution[i] + " ");
                }
            }
            return;
        }
        
        if(npush < source.length()) {
            s[top++] = source.charAt(npush);
            solution[depth] = 'i';
            dfs(depth+1, npush+1, npop);
            top--;
        }
        
        if(top > 0 && s[top - 1] == target.charAt(npop)) {
            solution[depth] = 'o';
            char temp = s[top-1];
            top--;
            dfs(depth+1, npush, npop+1);
            s[top++] = temp;
        }
        return;
    }
}

 

posted on 2018-02-03 22:02  NEU-2015  阅读(126)  评论(0编辑  收藏  举报

导航