浙大OJ 1004 回文栈 暴搜

🍑 ZOJ 1004 Anagrams by Stack
在这里插入图片描述
输入

madam
adamm
bahama
bahama
long
short
eric
rice

输出

[
i i i i o o o i o o 
i i i i o o o o i o 
i i o i o i o i o o 
i i o i o i o o i o 
]
[
i o i i i o o i i o o o 
i o i i i o o o i o i o 
i o i o i o i i i o o o 
i o i o i o i o i o i o 
]
[
]
[
i i o i o i o o 
]

🍑 案例模拟
🍤 循环字符串,栈操作只能改变它的起点
🍤 rice --> icer --> ceri --> eric --> rice

在这里插入图片描述
🍑 思路

🍤 暴力搜索所有出入栈的方案
🥞 只要源串还有字符,就可以入栈
🥞 只要栈顶与目标串当前元素相同,就可以出战
🥞 只要源串刚好枚举完 并且 目标串 已经得到,直接输出结果

🍤 搜索过程中 优先入栈操作(i < o),以保证字典序输出

import java.util.*;

public class Main
{
	static String s, t;// 源串 和 目标串
	static int len;// 记录字符串长度
	static Stack<Character> sta = new Stack<>();
	static ArrayList<Character> ans = new ArrayList<>();

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext())
		{
			s = sc.next();
			t = sc.next();
			len = s.length();
			while (!sta.isEmpty())// 清空栈
				sta.pop();
			System.out.println("[");
            if(len == t.length())//两串长度相等才搜索,不然无解
			    dfs(0, 0);
			System.out.println("]");
		}
	}

//	x y 分别记录 源串 和 目标串 的当前位置
	private static void dfs(int x, int y)
	{
		if (x == len && y == len)// 目标串已经得到
		{
			for (int i = 0; i < ans.size(); i++)
				System.out.print(ans.get(i) + " ");
			System.out.println();
			return;
		}

		if (x < len)// 源串未完全入栈
		{
			sta.push(s.charAt(x));
			ans.add('i');// 入栈
			dfs(x + 1, y);
			sta.pop();// 回溯 物归原主
			ans.remove(ans.size() - 1);
		}

		if (y < x && y < len && sta.peek() == t.charAt(y))
		{
			char tmp = sta.pop();
			ans.add('o');
			dfs(x, y + 1);
			sta.push(tmp);// 回溯
			ans.remove(ans.size() - 1);
		}
	}
}

🍑 OJ专栏
👨‍🏫 大佬题解

posted @ 2023-04-22 11:53  兑生  阅读(10)  评论(0编辑  收藏  举报  来源
Live2D