个人网站制作手绘,wordpress菜单显示图片,提高美誉度的网络营销方式,wordpress文章注册才能预览题目 Cpp 【问题描述】 字符环#xff08;来源#xff1a;NOI题库#xff09;。有两个由字符构成的环#xff0c;请写一个程序#xff0c;计算这两个字符环上最长公共字符串的长度。例如#xff0c;字符串“ABCEFAGADEGKABUVKLM”的首尾连在一起#xff0c;构成一个环来源NOI题库。有两个由字符构成的环请写一个程序计算这两个字符环上最长公共字符串的长度。例如字符串“ABCEFAGADEGKABUVKLM”的首尾连在一起构成一个环字符串”MADJKLUVKL”的首尾连在一起构成另一个环“UVKLMA”是这两个环的一个公共字符串。 【输入格式】 有两行每行一个不包含空格的字符串每行的字符串首尾相连即为一个环。 【输出格式】 一行输出一个整数表示这两个字符环上最长公共字符串的长度。 【输入样例】 ABCEFAGADEGKABUVKLM MADJKLUVKL 【输出样例】 6 【数据范围】 字符串长度不超过255 分析
就是找两个字符串的最大的连续交集。只不过字符串首尾相连。 思路
其实要考虑的只不过是最后一位的下一位是第一位而已。这也很简单直接将该字符串复制一份接到它后面即可。然后就可以循环找子集了。 代码 框架 int main(){return 0;
}输入字符串 #includecstdio //scanf()
char a[256], b[256];
int main(){scanf(%s %s, a, b);return 0;
}拼接字符串 注意不能直接用strcat()函数拼接 #includecstdio //scanf()
#includecstring //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;
}遍历字符串a的子集遍历头和尾并同时求出子集。详见该文张2.5版解题思路 #includecstdio //scanf()
#includecstring //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);lstrlen(a);for(int i0; il; i){memset(c, 0, sizeof(c));for(int j0; jl-i; j){c[j]a[ij];}}return 0;
}已经求出了一个字符串的子集现在直接判断该子集是否同时存在于另一个字符串中。如果存在就将该子集的长度比较存入变量中。 #includecstdio //scanf()
#includecstring //strcpy(), strcat(), memset(), strlen(), strstr()
#includecmath //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);lstrlen(a);for(int i0; il; i){memset(c, 0, sizeof(c));for(int j0; jl-i; j){c[j]a[ij];if(strstr(b, c)!NULL){ansfmax(ans, j1);}}}return 0;
}最后输出变量即可。 #includecstdio //scanf(), printf()
#includecstring //strcpy(), strcat(), memset(), strlen(), strstr()
#includecmath //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);lstrlen(a);for(int i0; il; i){memset(c, 0, sizeof(c));for(int j0; jl-i; j){c[j]a[ij];if(strstr(b, c)!NULL){ansfmax(ans, j1);}}}printf(%d, ans);return 0;
}答案
#includecstdio
#includecstring
#includecmath
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);lstrlen(a);for(int i0; il; i){memset(c, 0, sizeof(c));for(int j0; jl-i; j){c[j]a[ij];if(strstr(b, c)!NULL){ansfmax(ans, j1);}}}printf(%d, ans);return 0;
}