0
点赞
收藏
分享

微信扫一扫

Leetcode1642. 可以到达的最远建筑

归零者245号 03-05 07:30 阅读 5
c++算法

题目


分析

就是找两个字符串的最大的连续交集。只不过字符串首尾相连


思路

其实要考虑的只不过是最后一位的下一位是第一位而已。这也很简单,直接将该字符串复制一份接到它后面即可。然后就可以循环找子集了。


代码

  1. 框架

    int main(){
    	return 0;
    }
    

  2. 输入字符串

    #include<cstdio>	//scanf()
    char a[256], b[256]; 
    int main(){
    	scanf("%s %s", &a, &b);
    	return 0;
    }
    

  3. 拼接字符串
    注意,不能直接用strcat()函数拼接!

    #include<cstdio>	//scanf()
    #include<cstring>	//strcpy(), strcat(), memset()
    char a[256], b[256], c[256];
    int main(){
    	scanf("%s %s", &a, &b);
    	strcpy(c, a);
    	strcat(a, c);
    	memset(c, 0, sizeof(c));
    	strcpy(c, b);
    	strcat(b, c);
    	return 0;
    }
    

  4. 遍历字符串a的子集(遍历头和尾,并同时求出子集)。详见该文张2.5版解题思路

    #include<cstdio>	//scanf()
    #include<cstring>	//strcpy(), strcat(), memset(), strlen()
    char a[256], b[256], c[256];
    int l;
    int main(){
    	scanf("%s %s", &a, &b);
    	strcpy(c, a);
    	strcat(a, c);
    	memset(c, 0, sizeof(c));
    	strcpy(c, b);
    	strcat(b, c);
    	l=strlen(a);
    	for(int i=0; i<l; i++){
    		memset(c, 0, sizeof(c));
    		for(int j=0; j<l-i; j++){
    			c[j]=a[i+j];
    		}
    	}
    	return 0;
    }
    

  5. 已经求出了一个字符串的子集,现在直接判断该子集是否同时存在于另一个字符串中。如果存在,就将该子集的长度比较存入变量中。

    #include<cstdio>	//scanf()
    #include<cstring>	//strcpy(), strcat(), memset(), strlen(), strstr()
    #include<cmath>		//fmax()
    char a[256], b[256], c[256];
    int l, ans;
    int main(){
    	scanf("%s %s", &a, &b);
    	strcpy(c, a);
    	strcat(a, c);
    	memset(c, 0, sizeof(c));
    	strcpy(c, b);
    	strcat(b, c);
    	l=strlen(a);
    	for(int i=0; i<l; i++){
    		memset(c, 0, sizeof(c));
    		for(int j=0; j<l-i; j++){
    			c[j]=a[i+j];
    			if(strstr(b, c)!=NULL){
    				ans=fmax(ans, j+1);
    			}
    		}
    	}
    	return 0;
    }
    

  6. 最后,输出变量即可。

    #include<cstdio>	//scanf(), printf()
    #include<cstring>	//strcpy(), strcat(), memset(), strlen(), strstr()
    #include<cmath>		//fmax()
    char a[256], b[256], c[256];
    int l, ans;
    int main(){
    	scanf("%s %s", &a, &b);
    	strcpy(c, a);
    	strcat(a, c);
    	memset(c, 0, sizeof(c));
    	strcpy(c, b);
    	strcat(b, c);
    	l=strlen(a);
    	for(int i=0; i<l; i++){
    		memset(c, 0, sizeof(c));
    		for(int j=0; j<l-i; j++){
    			c[j]=a[i+j];
    			if(strstr(b, c)!=NULL){
    				ans=fmax(ans, j+1);
    			}
    		}
    	}
    	printf("%d", ans);
    	return 0;
    }
    


答案

#include<cstdio>
#include<cstring>
#include<cmath>
char a[256], b[256], c[256];
int l, ans;
int main(){
	scanf("%s %s", &a, &b);
	strcpy(c, a);
	strcat(a, c);
	memset(c, 0, sizeof(c));
	strcpy(c, b);
	strcat(b, c);
	l=strlen(a);
	for(int i=0; i<l; i++){
		memset(c, 0, sizeof(c));
		for(int j=0; j<l-i; j++){
			c[j]=a[i+j];
			if(strstr(b, c)!=NULL){
				ans=fmax(ans, j+1);
			}
		}
	}
	printf("%d", ans);
	return 0;
}

举报

相关推荐

0 条评论