UVa 732 Anagrams by Stack

本文深入探讨了C++中一种基于栈和向量的数据结构实现的字符串匹配算法。通过递归深度优先搜索(DFS)策略,算法巧妙地处理两个字符串的匹配过程,实现了从输入字符串到目标字符串的有效转换。文章详细解释了算法的工作原理,包括如何利用栈来存储字符,以及如何通过向量记录操作序列。此外,还提供了完整的C++代码示例,展示了算法的具体实现细节。

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;
const int MAXL = 10000000;
char s1[MAXL];
char s2[MAXL];
vector<char> ans;
stack<char> s;
int p1, p2, l; //p1->s1, p2->s2
void print()
{
  //cout << "p1=" << p1 << ' ' << "p2=" << p2 << endl;
 // cout << "size=" << s.size() <<endl;
    printf("%c", ans[0]);
    for (int i = 1; i < ans.size(); i++) {
      printf(" %c", ans[i]);
    }
    printf("\n");
}
void dfs()
{
  if (p2 == l) {
    print();
  }
  // i
  if (p1 < l) {
    s.push(s1[p1]);
    p1++;
    ans.push_back('i');
    dfs();
    s.pop();
    p1--;
    ans.pop_back();
  }
  // o
  if (p2 < l) {
    if (s.empty()) return;
    char ch = s.top();
    if (ch != s2[p2]) return;
    s.pop();
    p2++;
    ans.push_back('o');
    dfs();
    s.push(ch);
    p2--;
    ans.pop_back();
  }
}
void solve()
{
  ans.clear();
  while (!s.empty()) {
    s.pop();
  }
  printf("[\n");
  l = strlen(s1);
  int l2 = strlen(s2);
  p1 = 0;
  p2 = 0;
  if (l == l2) dfs();
  printf("]\n");
}
int main()
{
  //freopen("in.txt", "r", stdin);
  while (scanf("%s\n%s\n", s1, s2) != EOF) {
    solve();
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值