只需要固定长串,拿着短串移动就好了。
我是从右往左移动,需要注意的是要判断两头重叠部分(左端重叠和右端重叠)的大小关系。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstdlib> 5 #include <cstring> 6 7 using namespace std; 8 9 int main() 10 { 11 char s1[210]; 12 char s2[210]; 13 char s3[210]; 14 int i,j; 15 while(scanf("%s",s1)!=EOF) 16 { 17 scanf("%s",s2); 18 int len1=strlen(s1); 19 int len2=strlen(s2); 20 for(i=len1; i<len1+len2; i++) 21 { 22 s1[i]=‘0‘; 23 } 24 s1[i]=‘\0‘; 25 for(i=len2; i<len1+len2; i++) 26 s2[i]=‘0‘; 27 s2[i]=‘\0‘; 28 if(len1<len2) 29 { 30 strcpy(s3,s1); 31 strcpy(s1,s2); 32 strcpy(s2,s3); 33 int x=len1; 34 len1=len2; 35 len2=x; 36 } 37 // puts(s1); 38 // puts(s2); 39 int t=0; 40 int r=0; 41 for(i=1; i<=len1; i++) 42 { 43 44 for(j=len1-i; j<len1+len2-i; j++) 45 { 46 if((s1[j]-‘0‘)+(s2[j-len1+i]-‘0‘)>3) 47 break; 48 } 49 if(j==len1+len2-i) 50 t=i; 51 52 //printf("%d\n",t); 53 } 54 55 for(i=1; i<len2; i++) 56 { 57 for(j=0; j<len2-i; j++) 58 { 59 if(s1[j]-‘0‘+s2[j+i]-‘0‘>3) 60 break; 61 } 62 if(j==len2-i) 63 {r=i; 64 break;} 65 } 66 // printf("r=%d\n",r); 67 //int Max=max(r,t); 68 if(t==0&&r==0) 69 printf("%d\n",len1+len2); 70 else if(t==0&&r!=0) 71 printf("%d\n",len1+r); 72 else if(r==0&&t!=0) 73 { 74 if(t>len2) 75 t=len2; 76 printf("%d\n",len1+len2-t); 77 } 78 else 79 { 80 if(t>len2) 81 t=len2; 82 if(t>len2-r) 83 printf("%d\n",len1+len2-t); 84 else 85 printf("%d\n",len1+r);} 86 87 } 88 return 0; 89 }
原文:http://www.cnblogs.com/HsiaoYeekwan/p/6266920.html