[Algorithm] C++ longest common substring length

Longest common substring length

The longest common subsequence length of string A ending with i and string B ending with j maxlen[i][j]=max(maxlen[i][j-1], maxlen[i-1][j])

When the i-1th character of A is the same as the j-1th character of B maxlen[i][j] = maxlen[i-1][j-1] + 1;

#include <stdio.h>
#include <string.h>

#define N 256
int f(const char* s1, const char* s2)
{
 	int a[N][N];
	int len1 = strlen(s1);
	int len2 = strlen(s2);
	int i, j;
	
	memset(a, 0, sizeof(int)*N*N);
	int max = 0;
	for(i=1; i<=len1; i++){
		for(j=1; j<=len2; j++){
			if(s1[i-1] == s2[j-1]) {
				a[i][j] = a[i-1][j-1] + 1; 
				if(a[i][j] > max) 
					max = a[i][j];
			}
		}
	}
	
	return max;
}

int main()
{
	printf("%d\n", f("abcdkkk", "baabcdadabc"));
	return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/115005764