Anagrams by Stack
描述
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.
输入
The input will consist of several lines of input. The first line of each pair of input lines is to be considered as a source word (which does not include the end-of-line character). The second line (again, not including the end-of-line character) of each pair is a target word. The end of input is marked by end of file.
输出
For each input pair, your program should produce a sorted list of valid sequences ofi and o which produce the target word from the source word. Each list should be delimited by
[
]
and the sequences should be printed in "dictionary order". Within each sequence, eachi and o is followed by a single space and each sequence is terminated by a new line.
Process
A stack is a data storage and retrieval structure permitting two operations:
Pop - to retrieve the most recently pushed item
We will use the symbol i (in) for push ando (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 sequencei i o i o o produce the anagram OOF. So also would the sequencei i i o o o. You are to write a program to input pairs of words and output all the valid sequences ofi and o which will produce the second member of each pair from the first.
样例输入
madam
adamm
bahama
bahama
long
short
eric
rice
样例输出
[
i i i i o o o i o o
i i i i o o o o i o
i i o i o i o i o o
i i o i o i o o i o
]
[
i o i i i o o i i o o o
i o i i i o o o i o i o
i o i o i o i i i o o o
i o i o i o i o i o i o
]
[
]
[
i i o i o i o o
]
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
string a,b;
int len1 , len2;
//k 代表存i o s数组的长度 x y分别代表a b 字符串用了多少 k2代表存字符栈的长度 string1 string2 是io字符串 和 栈字符串
void dfs(int x,int y,string s1,string s2,int k,int k2)
{
string str1 = s1, str2 =s2,str3;
int i,j;
if(k == 2 * len1)
{
for(i = 0;i < str2.size(); i++)
{
cout << str2[i]<<" ";
}
cout << endl;
return;
}
if(x < len1)
{
dfs(x + 1, y,str1+a[x],str2+'i',k+1,k2+1);
}
if(str1[k2-1] == b[y] && y < len1 && k2)
{
str1.erase(k2-1,1);
dfs(x,y + 1,str1,str2 + 'o',k+1,k2-1);
}
}
main()
{
while(cin >> a >> b )
{
string s1,s2;
len1 = a.size();
len2 = b.size();
puts("[");
if(len1 == len2)
dfs(0,0,s1,s2,0,0);
puts("]");
}
}