首页 > 代码库 > 1004 Anagrams by Stack

1004 Anagrams by Stack

考察DFS的应用,用栈描述字符串的变化过程。

 1 #include <stdio.h> 2 #include <string.h> 3 int len1,len2; 4 char str1[100],str2[100],stk[100],ans[200]; 5  6 void output(int n){ 7     int i; 8     for(i=0;i<n;i++){ 9         printf("%c ",ans[i]);10     }11     printf("\n");12 }13 14 void go(int in,int out,int p,int top){15     if(top<0)16         return;17     if(in==len1 && out==len2){18         output(p);19         return;20     }21     if(in<len1){22         stk[top]=str1[in];23         ans[p]=i;24         go(in+1,out,p+1,top+1);25     }26     if(top>0 && out<len2 && stk[top-1]==str2[out]){27         ans[p]=o;28         go(in,out+1,p+1,top-1);29         stk[top-1]=str2[out];30     }31 }32 33 int main(){34     while(scanf("%s%s",str1,str2)>=0){35         len1=strlen(str1);36         len2=strlen(str2);37         printf("[\n");38         if(len1==len2)39             go(0,0,0,0);40         printf("]\n");41     }42     return 0;43 }

 

1004 Anagrams by Stack