0

我的任务如下:

在字符串匹配中,我们在另一个字符串(文本)中寻找一个字符串(模式)的实例。我们正在寻找故障(不匹配)数量最少的实例。

例如,如果模式是“camb”并且文本是“caammbd”,我们会比较“位置”: 1. 比较“camb”和“caam”,这会显示 2 个不匹配(m 与 a,b 与 m)。2. 将“camb”与“aamm”进行比较,显示 2 个不匹配(m 与 a,b 与 m)。等等....

我的 prgoram 从用户那里读取两个字符串并尝试找到最小的数字并返回它的“位置”:

int misPattern(char str[], char pattern[]){
    int count = 0, maxCount = 0, worstPattern = 0, i = 0, j = 0, z = 0,
    patternNum = 1; 
    /*in order to make minimal tests, we must have each string's length*/
    int testsMade = 0;
    int numOfTests = (strlen(str, MAX_LEN + 1)) - (strlen(pattern, MAX_LEN + 1));
    while (str[i] != '\0' && testsMade<=numOfTests){
        z = i; count = 0;
        while (pattern[j] != '\0'){
            if (str[z] != pattern[j])
                count++;
            j++;
            z++;
        }
        j = 0;
        i++;
        if (count > maxCount){
            maxCount= count;
            worstPattern = patternNum;
        }
        patternNum++;
        testsMade++;
    }
    printf("%d\n", count);
    return worstPattern;
}

最差模式应该代表不匹配最少的位置。

正如您可能想象的那样,这里出了点问题。从调试器看来,我的比较并不顺利。正如调试器所示,字符串读得很好。

谢谢您的帮助。

4

1 回答 1

0
int misPattern(char str[], char pattern[]){
    int count = 0, minCount = 0, worstPattern = 0, i = 0, j = 0, z = 0, patternNum = 0; 
    /*in order to make minimal tests, we must have each string's length*/
    int testsMade = 0;
    int numOfTests = (strlen(str, MAX_LEN + 1)) - (strlen(pattern, MAX_LEN + 1));

    /*if the pattern is longer
    than the text than return -1, and 
     if the strings are   `equal         also     return -1*/`
    if (strcmp(str,pattern)<=0)
        return -1;

    /*initial value for minCount. we have to make sure minCount is initilized at least once*/
    while (str[i] != '\0' && (minCount == 0) && testsMade<=numOfTests){
        z = i;
        while (pattern[j] != '\0'){
            if (str[z] != pattern[j])
                minCount++;
            j++;
            z++;
        }
        testsMade++;
        j = 0;
        i++;
        patternNum++;
    }

        printf("number of first minimal mismatches is %d\n", minCount);
        printf("i is %d j is %d\n", i, j);

    while (str[i] != '\0' && testsMade<=numOfTests){
        z = i; count = 0;
        while (pattern[j] != '\0'){
            if (str[z] != pattern[j])
                count++;

            j++;
            z++;
        }
        j = 0;
        i++;
        if (count < minCount){
            minCount= count;
            worstPattern = patternNum;
        }
        patternNum++;
        testsMade++;
    }

    return worstPattern;
}

这是我的最后一个程序,在理解我的错误之后。谢谢你们。

于 2013-11-09T18:39:14.033 回答