求两个字符串公共子序列的最大长度(参考阿里巴巴2015研发笔试)(简单)

来源:互联网 发布:落叶而知秋 编辑:程序博客网 时间:2024/05/21 17:35

题目:给定字符串s1,s2,均由小写字母祖闯,要求在s1中找出以同样顺序连续出现在s2中的最长连续序列的长度;如s1=“acaccbabb”,s2 = “acbac”,那么s1,s2的最大公共子串为“cba”,对应的长度为3。

思路:这里采用暴力匹配方法,时间复杂度为O(mn)

具体代码如下:

#include<stdio.h>#include<string.h>//寻找两个字符串最长公共子序列的长度 int bfMatch(char *a,char *b,int max){int result,i,j,itemp;max = 0;for(i=0;a[i]!='\0';i++){itemp = i;result = 0;for(j=0;b[j]!='\0';j++){if(a[itemp] == b[j]){result ++;if(max < result)max = result;itemp ++;}else{result = 0;//结果置0 ; itemp = i;//itemp回溯至i,从j的当前位置开始搜索; }}if(itemp == strlen(a))//若itemp已搜索至a串末尾 break;}return max;} int main(){char b[] = "acbac";char a[] = "acaccbabb";printf("%d\n",bfMatch(a,b,0));return 0;}




0 0