c - 简单字符串匹配期间比较的字符数

标签 c string algorithm

我被要求查找在简单字符串匹配期间比较的字符数。这是我们被要求实现的功能:

// Count the number of characters compared while finding all occurences of the pattern in the given text
// Characters must be matched from left to right
int charactersCompared(char *pattern, char *text);

因此,如果文本是:“ABCEDF”并且模式是:“EF”,我使用暴力方法比较的字符数将为 6(将文本的第一个字母与模式的第一个字母。如果不匹配,则再次将文本的第二个字母与模式的第一个字母进行比较。 如果匹配,则继续比较文本和模式的下一个字母等)

在通过很多例子弄清楚逻辑后,我这样实现了上面的功能:

int charactersCompared(char *pattern, char *text)
{
    int i,j,comp=0; 
    int flag;

    for(i=0;text[i]!='\0';i++)    //iterating through all the letters of text
    {
        for(j=0;pattern[j]!='\0';j++)
        {
            comp++;             //to count one comparision. 
            if(text[i+j]==pattern[j])   //to check if similar to pattern
            {
                flag=1;          
                continue;
            }
            else
            {
                if(flag==1)
                {
                    flag=0;
                    comp--;
                }
                break;
            }
        }
    }
    //printf("VALUE OF C=%d\n",comp);
    return comp;
}

这对于 (ABCDEF,EF) 对(其中计数为 6)效果很好,但对于其他包含文本中多次出现该模式的测试用例则不起作用,例如: 文本:ABCDEFGHEIEF 图案:EF

我应该得到 14 次比较,而我的输出是 12 次。我不明白我错过了什么。

如果有人能指出什么是错误的逻辑,那将会有很大的帮助。或者如果有更简单的方法来做到这一点,建议表示赞赏。唯一的限制是该方法必须是暴力方法(即我无法真正更改比较每个字符串的每个字符的部分)。

感谢您的宝贵时间!

最佳答案

请注意,最坏​​的情况是 n(m-n+1) ,其中 n 是模式长度,m 是长度的文本。现在,由于您只想计算比较,因此不需要变量 flag。喜欢KISS原理。

for(i=0;text[i]!='\0';i++)    //iterating through all the letters of text
{
    for(j=0;pattern[j]!='\0';j++)
    {
        comp++;             //to count one comparison. 
        if(text[i+j]==pattern[j])   //to check if similar to pattern
            continue;
        break;
     }
}
printf("VALUE OF C=%d\n",comp);

关于c - 简单字符串匹配期间比较的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812335/

相关文章:

c - 如何创建在 .txt 文件中搜索单词并计算它在 C 中出现的次数的代码?

C 读取由空格分隔且字长不受限制的文本文件

c - 在我的 c 代码中删除重复项时出现错误

algorithm - 为什么当我们将 G 中每条边的成本更改为 c'= log17(c) 时,G 中的每个 MST 仍然是 G' 中的 MST(反之亦然)?

python - 查找范围内的圆间隔

python - 与判断列表中的项目相比,在多大程度上搜索将列表转换为集合的成本将得到补偿?

c - 使用 pthread 时 Accept() 返回对 stdout (1) 的引用

c - C语言中如何获取子串?

R - 从两个单词的字符串中提取城市名称

Java Nice 格式 double