The longest common substring problem solution

Title Description
Given two strings a, b, the conventional k chance to modify the characters in the string, so that the longest common substring modified two longest string.
Each modification can choose a, an arbitrary position in a string b modify an arbitrary character string.

Input format:
The first line includes a positive integer k.
The second and third rows, respectively of the input string a, b. (The length of each string does not exceed 500)

Output format:
the output is an integer representing the length of the longest common substring of two strings modified.

Outline of Solution
Violence: using two heavy cycle, selected in different starting positions a, b string, calculating a modified maximum of longest common subsequence lengths of the two strings of the string after the k-th comparing the final result obtained.

The complete code

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

int main()
{
    int k, n1, n2, ans = 0, count, i, j, p, q;
    char a[505], b[505];
    scanf("%d", &k);
    getchar();
    gets(a);
    gets(b);
    n1 = strlen(a);
    n2 = strlen(b);

    for (i = 0; i < n1; i++) {
        for (j = 0; j < n2; j++) {
            p = i;
            q = j;
            count = 0;
            while (count != k && p != n1 && q != n2) {
                if (a[p] != b[q]) {
                    count++;
                }
                p++;
                q++;
            }
            if (p - i > ans) {
                ans = p - i;
            }
        }
    }
    printf("%d", ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/dump16/p/12409981.html