问题描述:输入两个字符串,求得两个字符串的最大字串。
阅读(1211) | 评论(0) | 转发(1) |
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
问题分析:为了求得两个字符串的最大字串,其中一种思路是这样的。两个字符窗分别为a和b (strlen(a)<=strlen(b)),取长度较小的那个字串b,假如它的长度为n,第一次用长度为n的子串进行与a匹配,如果没有匹配成功,用n-1长度的所有子串与a进行匹配,如果没有匹配成功,继续用长度减小的下一个所有子串进行匹配,直到匹配成功。
程序实现:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- char *max_str(char *long_str, char *short_str)
- {
- char *tmp = NULL;
- int i, j;
-
- tmp = malloc(256);
- for(i = strlen(short_str); i > 0; i--) {
- for(j = strlen(short_str)-1; j >= i-1; j--) {
- memcpy(tmp, &short_str[j-i+1], i);
- tmp[i] = 0;
- if(strstr(long_str, tmp) != NULL) {
- return tmp;
- }
- }
- }
- return NULL;
- }
-
- int main()
- {
- char *str1 = malloc(256);
- char *str2 = malloc(256);
- char *res = NULL;
-
- scanf("%s %s", str1, str2);
- if(strlen(str1) > strlen(str2)) {
- res = max_str(str1, str2);
- } else {
- res = max_str(str2, str1);
- }
- printf("str1:%s\n", str1);
- printf("str2:%s\n", str2);
- printf("max sub string:%s\n", res);
-
- free(str1);
- free(str2);
- free(res);
- return 0;
- }
测试结果:
- ^_^[sunny@sunny-laptop ~/DS]16$ ./a.out
- opencv\@bs][dasf
- \@
- str1:opencv\@bs][dasf
- str2:\@
- max sub string:\@
- ^_^[sunny@sunny-laptop ~/DS]17$ ./a.out
- hello
- hello
- str1:hello
- str2:hello
- max sub string:hello
- ^_^[sunny@sunny-laptop ~/DS]18$ ./a.out
- hello
- he
- str1:hello
- str2:he
- max sub string:he
- ^_^[sunny@sunny-laptop ~/DS]19$
- ^_^[sunny@sunny-laptop ~/DS]16$ ./a.out
程序说明:在主函数中得到两个字符串,并且调用max_str()函数进行匹配。其中的char * strstr(char *a, char * b)函数是string.h中的一个函数,该函数的作用是定位字串,如果b在a中出现的话,就返回b,否则返回NULL。
相关热门文章
给主人留下些什么吧!~~
评论热议