原题:
How can anagrams result from sequences of stack operations? There are two sequences of stack operators which can convert TROT to TORT:
[
i i i i o o o o
i o i i o o i o
]
where i stands for Push and o stands for Pop. Your program should, given pairs of words produce sequences of stack operations which convert the first word to the second.
A stack is a data storage and retrieval structure permitting two operations:
Push - to insert an item and
Pop - to retrieve the most recently pushed item
We will use the symbol i (in) for push and o (out) for pop operations for an initially empty stack of characters. Given an input word, some sequences of push and pop operations are valid in that every character of the word is both pushed and popped, and furthermore, no attempt is ever made to pop the empty stack. For example, if the word FOO is input, then the sequence:
i i o i o o is valid, but
i i o is not (it's too short), neither is
i i o o o i (there's an illegal pop of an empty stack)
Valid sequences yield rearrangements of the letters in an input word. For example, the input word FOO and the sequence i i o i o o produce the anagram OOF. So also would the sequence i i i o o o. You are to write a program to input pairs of words and output all the valid sequences of i and o which will produce the second member of each pair from the first.
题意:
依然是栈的问题,给出两个字符串,问以第一个字符串能否通过进出栈转化为第二个字符串,如果可以则表示出进出栈顺序。
题解:
因为这个题给出的字符串中有相同的字符了,所以不能像上一个题直接用栈顶元素来比较,所以用深搜来搜索能否输出,深搜的同时定义输出数组来记录进出栈顺序。深搜思路也比较简单,先是进栈然后深搜然后出栈,截止条件是sourpos==序列长度,然后如果栈顶元素和要求序列相同,就出栈然后深搜再记录。(感觉好难说.....)
代码:AC
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
char sourStr[1000];
char destStr[1000];
int outputStr[2000];
stack<char> *st;
int sourPos,destPos;
int inputLen;
void output()
{
int i;
for(i=0;i<inputLen*2;i++)
printf("%c ",outputStr[i]==0?'o':'i');
printf("\n");
}
void dfs(int k)
{
if(destPos==inputLen)
output();
else
{
if(sourPos<inputLen)
{
outputStr[k]=1;
st->push(sourStr[sourPos]);
sourPos++;
dfs(k+1);
sourPos--;
st->pop();
outputStr[k]=-1;
}
if(!st->empty() && st->top()==destStr[destPos])
{
outputStr[k]=0;
st->pop();
destPos++;
dfs(k+1);
destPos--;
st->push(destStr[destPos]);
outputStr[k]=-1;
}
}
}
int main()
{
st=new stack<char>;
while(scanf("%s\n%s",&sourStr,&destStr)!=EOF)
{
printf("[\n");
sourPos=destPos=0;
inputLen=strlen(sourStr);
dfs(0);
printf("]\n");
}
return 0;
}