zoj 1004练习题Java

import java.util.*;
/*
 * 功能:zoj1004
 * 说明:题目要求输入两组字符串,str1,str2,输出所有str1变成str2的push、pop操作
 */
public class Main {


static class myChar{
public char c;
public myChar(char c) {
// TODO Auto-generated constructor stub
this.c = c;
}
}
static class DFS{
int len;                                        //保存字符串长度
Vector save = new Vector();    //保存io操作序列
Stack stack = new Stack(); //暂存数据,模拟栈操作
char[] source; //源字符串
char[] mark; //目标字符串
/*
* 功能:构造函数
* 输入:源字符串,目标字符串
* 返回:void
*/
public DFS(String source, String mark){
this.source = source.toCharArray();
this.mark = mark.toCharArray();
len = source.length();
}
/*
* 作用:深度优先遍历
* 输入:in push操作次数
*   out pop操作次数
* 返回:void
* 说明:当输入输出操作次数等于操作字符串长度时说明得到一个可行的io序列,结束
*   输入次数小于字符串长度时继续进行push操作,并调用自身深度遍历
* 输出次数out小于输入次数事,若目标字符串
*/
void dfs(int in, int out){
if(in==len && out == len){
for(int i=0; i<save.size(); i++){
char c = ((myChar)save.get(i)).c;
System.out.print(c);
System.out.print(' ');
}
System.out.println();
}
if(in < len){
stack.push(new myChar(source[in]));
save.add(new myChar('i'));
dfs(in+1, out);
save.remove(save.size()-1);
stack.pop();
}
if(out < in && mark[out]==((myChar)stack.peek()).c){
myChar tmpChar = (myChar)stack.pop();
save.add(new myChar('o'));
dfs(in, out+1);
save.remove(save.size()-1);
stack.push(tmpChar);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String source = scanner.nextLine();
String mark = scanner.nextLine();

System.out.println("[");
DFS myDFS = new DFS(source, mark);
myDFS.dfs(0, 0);
System.out.println("]");
}
scanner.close();
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值