[JAVA][ZOJ 1004][Anagrams by Stack]

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import java.io.BufferedInputStream;  
  2. import java.util.Scanner;  
  3.   
  4. public class Main {  
  5.     static String start;// record the first str  
  6.     static String end;// record the rearranged str  
  7.   
  8.     public static void dfs(char[] stack, char[] sequence, int posInStart, int posInEnd, int posInStack) {  
  9.         if (posInStart + posInEnd == start.length() * 2) {// if all the letter has been rearranged  
  10.             for (int i = 0; i < sequence.length; i++) {  
  11.                 System.out.print(sequence[i] + " ");// output the sequence  
  12.             }  
  13.             System.out.println();  
  14.         }  
  15.         if (posInStart < start.length()) {  
  16.             sequence[posInStart + posInEnd] = 'i';  
  17.             stack[++posInStack] = start.charAt(posInStart);// push in  
  18.             dfs(stack, sequence, posInStart + 1, posInEnd, posInStack);  
  19.             posInStack--;// pop out  
  20.         }  
  21.         if (posInStack >= 0 && posInEnd < end.length() && stack[posInStack] == end.charAt(posInEnd)) {// pop out  
  22.             sequence[posInStart + posInEnd] = 'o';  
  23.             posInStack--;// pop out  
  24.             dfs(stack, sequence, posInStart, posInEnd + 1, posInStack);  
  25.             stack[++posInStack] = end.charAt(posInEnd);  
  26.         }  
  27.     }  
  28.   
  29.     public static void main(String[] args) {  
  30.         Scanner sc = new Scanner(new BufferedInputStream(System.in));  
  31.         while (sc.hasNext()) {  
  32.             start = sc.next();  
  33.             end = sc.next();  
  34.             char[] stack = new char[start.length() * 2];// use array as the stack  
  35.             char[] sequence = new char[start.length() * 2];// record the operation seq, it will have (start.length() * 2) times operations  
  36.             System.out.println("[");  
  37.             dfs(stack, sequence, 00, -1);  
  38.             System.out.println("]");  
  39.         }  
  40.     }  
  41. }  





最近写的几道题都用到了dfs,用数组代替栈的使用,控制好stack数字下标就没什么大问题,难得一次AC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值