Over a million developers have joined DZone.

Find The Longest Duplicated Substring In C

DZone's Guide to

Find The Longest Duplicated Substring In C

Free Resource
The programme finds the longest substring that is duplicated.


#define MAXN 5000000

int n;
char c[MAXN], *a[MAXN];

int pstrcmp(const void **x, const void **y) {
	return strcmp(*(char**)x, *(char**)y);

int comlen(char *p, char *q) {
	int i = 0;
	while (*p && (*p++ == *q++))
	return i;

int main(int argc, char *argv[]) {
	int i;
	FILE *fi = fopen("james.txt", "r");
	char ch;
	while (fread(&ch, 1, 1, fi)) {
		a[n] = &c[n];
		c[n++] = ch;
	c[n] = 0;

	qsort(a, n, sizeof(char*), pstrcmp);

	int maxlen = 0, maxi = 0;
	for (i = 0; i < n-1; ++i)
		if (comlen(a[i], a[i+1]) > maxlen) {
			maxlen = comlen(a[i], a[i+1]);
			maxi = i;
	printf("%.*s\n", maxlen, a[maxi]);

	return 0;


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}