Anagrams by Stack python

21 篇文章 0 订阅
def dst(push, pop, olst, dlst, s, t):
    #global result
    l = len(olst)
    if push==l and pop==l:
        print t
        return 0
    
    if len(s)==0:
        s.append(olst[push])
        push = push+1
        t.append('i')
        dst(push, pop, olst, dlst, s, t)
    else:
        temp = s.pop()
        if temp==dlst[pop]:
            t.append('o')
            pop = pop+1
            dst(push, pop, olst, dlst, s, t)
        else:
            s.append(temp)
            s.append(olst[push])
            push = push+1
            t.append('i')
            dst(push, pop, olst, dlst, s, t)
    
def Compare(olst, dlst):
    l = len(olst)
    s = []
    t = []
    push = 0
    pop = 0
    #print '[\n'
    dst(push, pop, olst, dlst, s, t)
    #print ']\n'
        
org = raw_input()
dis = raw_input()
olst = []
dlst = []
for i in org:
    olst.append(i)
for j in dis:
    dlst.append(j)   
while org or dis:
    ol = len(olst)
    dl = len(dlst)
    if ol!=dl:
        print '[\n]\n'
    else:
        Compare(olst, dlst)
    org = raw_input()
    dis = raw_input()
    olst = []
    dlst = []
    for i in org:
        olst.append(i)
    for j in dis:
        dlst.append(j)


摘抄:

c++代码:

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

string s1,s2;
stack<char> cs;
vector<char> io;
int l;//当前案例,字符串的长度

void Prints()
{
    for(int i=0;i<io.size();i++)
        cout<<io[i]<<" ";
    cout<<endl;
}

//in表示入栈数量,out表示出栈数量
void dfs(int in,int out)
{
    char t;
    if( in==l && out==l )//如果入栈和出栈数量都等于字符串长度,则表示已得到一个成功解
    {
        Prints();
        return;
    }

    if( in<l )
    {
        cs.push(s1[in]);
        io.push_back('i');
        dfs(in+1,out);
        cs.pop();
        io.pop_back();
    }
    if( out<in && out <l && cs.top()==s2[out] )
    {
        t = cs.top();
        cs.pop();
        io.push_back('o');
        dfs(in,out+1);
        cs.push(t);
        io.pop_back();
    }
}

int main()
{
    while(cin>>s1>>s2)
    {
        l=s1.length();
        cout<<"["<<endl;
        dfs(0,0);
        cout<<"]"<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值