题目描述:
通过栈交换字母顺序。给定两个字符串,要求所有的进栈和出栈序列(i表示进栈,o表示出栈),使得字符串1在求得的进出栈序列的操作下,变成字符串2。输出结果需满足字典序。例如TROT 到 TORT:
[
i i i i o o o o
i o i i o o i o
]
这一题用到的算法为回溯,其中有一些简单的栈的应用,思路难度不大,但是要注意细节。
首先要设立三个字符串,分别是start(输入),mid(栈)和ans(由出栈构成的字符串),每一次可以入栈(start的一个字符压入mid)或者出栈(mid的一个字符压入ans),然后将ans与end(要求转化成的最终字符串)进行局部比较,判断是否继续,这也是一个简单的剪枝。
事实上,只要对栈较为熟悉,这一题应能不那么困难地完成。特别地,题目有多组数据,应该使用while/scanf结构输入。
代码如下:
#include#include #include typedef struct { char ch[1000]; int top; int last; } chStack; typedef struct { int operation[1000]; int top; } inStack; chStack start; chStack end; chStack mid; chStack ans; inStack op; void dfs(); int issame(); void output(); int main() { //input and init while (scanf("%s%s", start.ch, end.ch) != EOF) { start.last = strlen(start.ch) - 1; end.last = strlen(end.ch) - 1; start.top = -1; end.top = -1; mid.top = -1; ans.top = -1; op.top = -1; printf("[n"); dfs(); printf("]n"); } } void dfs() { if (ans.top == end.last && issame()) { output(); } if (start.top < start.last) { start.top++; mid.top++; mid.ch[mid.top] = start.ch[start.top]; op.top++; op.operation[op.top] = 1; dfs(); op.top--; mid.top--; start.top--; } if (mid.top != -1) { ans.top++; ans.ch[ans.top] = mid.ch[mid.top]; mid.top--; op.top++; op.operation[op.top] = 0; if (issame()) { dfs(); } op.top--; mid.top++; mid.ch[mid.top] = ans.ch[ans.top]; ans.top--; } } int issame() { int i; for (i = 0; i <= ans.top; i++) { if (ans.ch[i] != end.ch[i]) { return 0; } } return 1; } void output() { int i; for (i = 0; i <= op.top; i++) { if (op.operation[i] == 1) { printf(" i" + !i);//这里使用了简单的技巧,使得行首行尾没有空格 } else { printf(" o" + !i); } } printf("n"); }



