hdu 1515 Anagrams by Stack
2013-10-02 20:08
387 查看
题解:
第一:两个字符不相等(即栈顶字符与目标字符不相等);这种情况很容易处理,将匹配word的下一个字符入栈,指针向后挪已为继续递归。
第二:两个字符相等(即栈顶字符与目标字符相等);这种情况有两种选择
(1)字符出栈,并将目标word的指针向后挪一位,继续递归;
(2)将匹配word的下一个字符入栈,指针向后挪一位,继续递归;
每一次递归用path记录下来路径。当目标word的指针超过最后一位了,说明成功,此时将path输出。
第一:两个字符不相等(即栈顶字符与目标字符不相等);这种情况很容易处理,将匹配word的下一个字符入栈,指针向后挪已为继续递归。
第二:两个字符相等(即栈顶字符与目标字符相等);这种情况有两种选择
(1)字符出栈,并将目标word的指针向后挪一位,继续递归;
(2)将匹配word的下一个字符入栈,指针向后挪一位,继续递归;
每一次递归用path记录下来路径。当目标word的指针超过最后一位了,说明成功,此时将path输出。
#include<stdio.h> #include<string.h> #include<stack> using namespace std; char str1[1005],str2[1005]; int len1,len2; char path[2005]; void test(int x,int y,stack<char> st,int t) { int j; if(y==len2) { printf("i "); for(j=0; j<t; j++) printf("%c ",path[j]); printf("\n"); return ; } if(st.empty ()) { st.push(str1[x+1]); path[t]='i'; test(x+1,y,st,t+1); st.pop(); return ; } char cur=st.top (); if(x==len1 && cur!=str2[y]) return ; st.push(str1[x+1]); path[t]='i'; test(x+1,y,st,t+1); st.pop(); if(cur==str2[y]) { st.pop(); path[t]='o'; test(x,y+1,st,t+1); st.push(str1[x]); } return ; } int main() { int i,j; while(scanf("%s%s",str1,str2)!=EOF) { len1=strlen(str1); len2=strlen(str2); printf("[\n"); if(len1<len2) { printf("]\n"); continue; } stack<char> st; st.push(str1[0]); test(0,0,st,0); printf("]\n"); } return 0; }
相关文章推荐
- HDU ACM 1515 Anagrams by Stack
- hdoj 1515 Anagrams by Stack(dfs)
- ZOJ 1004 Anagrams by Stack
- HDU 1515 - Anagrams by Stack
- Anagrams by Stack
- 【算法】算法之美—Anagrams by Stack
- Anagrams by Stack
- ZOJ&nbsp;1004&nbsp;Anagrams&nbsp;by&nbsp;Stack
- hdu 1515/zoj 1004 Anagrams by Stack
- HDU - 1515 Anagrams by Stack
- ZOJ 1004 : Anagrams by Stack 体验回溯搜索
- HDU 1515 Anagrams by Stack【深搜】
- ZOJ1004 Anagrams by Stack
- ZOJ-1004 Anagrams by Stack(栈+深搜)
- ZOJ-1004(AOJ-466) Anagrams by Stack
- Anagrams by Stack
- ZOJ Problem Set - 1004-Anagrams by Stack
- zoj1004 Anagrams by Stack dfs
- TOJ 1183 HDU 1515 ZOJ 1004 Anagrams by Stack /深搜+栈
- 2018_2_5_Anagrams by Stack_栈_模拟_回溯_递归