ZOJ-1004

本文介绍了一种利用深度优先搜索(DFS)回溯的方法来解决字符串匹配问题。通过构建状态机并使用栈来跟踪当前匹配状态,实现字符串的高效匹配。详细解释了算法的实现步骤、关键逻辑以及如何通过递归调用DFS函数来遍历所有可能的匹配路径,最终确定匹配结果。

基本思路就是DFS回溯

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class ZOJ1004
{
	static Stack<Character> stack = new Stack<Character>();
	static List<String> result = new ArrayList<String>();

	static void dfs(String io, String from, String to)
	{
		if (to.isEmpty())
		{
			result.add(io);
			return;
		}

		if (!stack.isEmpty() && stack.peek() == to.charAt(0))
		{
			stack.pop();
			dfs(io + 'o', from, to.substring(1));
			stack.push(to.charAt(0));
		}
		if (!from.isEmpty())
		{
			stack.push(from.charAt(0));
			dfs(io + 'i', from.substring(1), to);
			stack.pop();
		}
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext())
		{
			String s1 = sc.nextLine();
			String s2 = sc.nextLine();
			result.clear();
			dfs("", s1, s2);
			Collections.sort(result);
			System.out.println("[");
			for (String s : result)
			{
				char[] chs = s.toCharArray();
				for (int i = 0; i < chs.length; i++)
					System.out.print(chs[i] + " ");
				System.out.println();
			}
			System.out.println("]");
		}
		sc.close();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值