Skip to content

Instantly share code, notes, and snippets.

@studentbrad
Created October 25, 2019 19:37
Show Gist options
  • Save studentbrad/2b1b84597679a491b1d09559e33a0c01 to your computer and use it in GitHub Desktop.
Save studentbrad/2b1b84597679a491b1d09559e33a0c01 to your computer and use it in GitHub Desktop.
The longest sub-string length in a character array
int longest_substring(char* s)
{
int string_length = strlen(s);
if (string_length == 0)
{
return 0;
}
// form the string matrix
int string_matrix[string_length][string_length];
for (int i = 0; i < string_length; i++)
{
for (int j = 0; j < string_length; j++)
{
string_matrix[i][j] = 0;
}
}
for (int i = 0; i < string_length; i++)
{
int temp = 0;
for (int j = i + 1; j < string_length; j++)
{
if (*(s + i) == *(s + j))
{
string_matrix[i][j] = ++temp;
}
else
{
string_matrix[i][j] = temp;
}
}
}
// form the concatenation matrix
int concatenation_matrix[string_length][string_length];
for (int i = 0; i < string_length; i++)
{
for (int j = 0; j < string_length; j++)
{
concatenation_matrix[i][j] = 0;
}
}
for (int i = 0; i < string_length; i++)
{
for (int j = i; j < string_length; j++)
{
// add the jth row to the ith row
for (int k = 0; k < string_length; k++)
{
concatenation_matrix[i][k] += string_matrix[j][k];
}
// check if concetenation is redundant
bool redundant = false;
for (int k = 0; k < string_length - 1; k++)
{
if ((concatenation_matrix[i][k + 1] - concatenation_matrix[i][k]) > 1)
{
redundant = true;
break;
}
}
// subtract the jth row from the ith row if redundant
if (redundant)
{
for (int k = 0; k < string_length; k++)
{
concatenation_matrix[i][k] -= string_matrix[j][k];
}
}
}
}
// find the row with the most zeros
int index = 0;
int length = 0;
for (int i = 0; i < string_length; i++)
{
int count = 0;
for (int j = i; j < string_length; j++)
{
if (concatenation_matrix[i][j] == 0)
{
count++;
}
else
{
break;
}
}
if (count > length)
{
length = count;
index = i;
}
}
return length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment