1004 Anagrams by Stack

本文介绍了一个使用C++实现的递归算法示例,该算法利用两个栈来处理字符串输入,演示了如何通过递归进行字符串匹配。代码详细展示了如何定义递归函数并运用栈数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// C++Exercise.cpp : 定义控制台应用程序的入口点。
//

#include<iostream>
#include<string>
#include<stack>
using namespace std;

string first, second;
int len;

void dfs(stack<char> &st,stack<char> data,int n_push,int n_pop){
	if (n_push == len&&n_pop == len){
		stack<char> out;
		stack<char> st1 = st;
		while (!st1.empty()){
			char temp = st1.top();
			st1.pop();
			out.push(temp);
		}
		while (!out.empty()){
			cout << out.top();
			out.pop();
			cout << " ";
		}
		cout <<endl;
		return;
	}
	if (n_push < len){
		st.push('i');
		data.push(first[n_push]);
		n_push++;
		dfs(st,data,n_push,n_pop);
		data.pop();
		st.pop();
		n_push--;
	}
	if (!data.empty() &&n_pop<len&& data.top() == second[n_pop]){
		data.pop();
		n_pop++;
		st.push('o');
		dfs(st, data, n_push, n_pop);
		st.pop();
		n_pop--;
	}
}

int main()
{
	while (cin >> first >> second){
		cout << '[' << endl;
		if (first.size() == second.size()){
			len = first.size();
			stack<char> st;
			stack<char> data;
			dfs(st,data,0,0);
 		}
		cout << ']' << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值