• 字符串匹配算法


    字符串匹配算法有非常多种,最为经常使用的有KMP算法、普通算法。

    1、普通算法:此算法是效率最低的算法。时间复杂度为O(NM)。

    程序例如以下:

    bool str_match(const char * str1, const char * str2)//O(P*T)
    {
    	assert(str1 != NULL && str2 != NULL);
    	int k = 0;
    	for (unsigned int i = 0; i < strlen(str1); i ++)
    	{
    		k = i;
    		for (unsigned int j = 0; j < strlen(str2); j ++)
    		{
    			if (*(str1 + k++) == *(str2 + j))
    			{
    				if (j == strlen(str2)-1)
    					return true;
    			}
    			else 
    				break;
    		}
    	}
    	return false;
    }


    2、KMP算法。KMP算法能够说是在普通算法上的改进的算法,在普通算法中,在字符串P中每一次仅仅移动一个字符,而在KMP算法中,依据后缀表达式同样的方法。能够跳过几个字符,在算法运行開始须要找出每次移动的字符数。

    程序例如以下:

    ////---------------------------------------------------KMP-------------//
    void findNext(const char * strP, int * next)
    {
    	assert(strP != NULL && next != NULL);
    	int lenP = strlen(strP);
    	*next = -1;
    	int i = 0;
    	int j = -1;
    	while (i < lenP)
    	{
    		while (j == -1 || j < lenP && *(strP+i) == *(strP + j) )
    		{
    			j++;
    			i++;
    			if(*(strP+i) != *(strP + j))
    				next[i] = j;
    			else
    				next[i] = next[j];
    		}
    		j = next[j];
    	}
    }
    int KMP(const char * strP, const char *strT)
    {
    	assert(strP != NULL && strT != NULL);
    	int lenP = strlen(strP);
    	int * next = new int[lenP];
    	findNext(strP,next);
    	int i = 0;
    	int j = 0;
    	int lenT = strlen(strT);
    	while (i <= strT-strP)
    	{
    		while (j == -1 || j < lenP && *(strP+j) == *(strT + i))
    		{
    			i++;
    			j++;
    		}
    		if (j == lenP)
    		{
    			return i - lenP;
    		}
    		j = *(next+j);
    	}
    	delete [] next;
    	return -1;
    }
    //--------------------------------------end of KMP-------------------------------------//




  • 相关阅读:
    Jedis scan及其count的值
    redis中KEYS、SMEMBERS、SCAN 、SSCAN 的区别
    Windows环境下RabbitMQ的启动和停止命令
    HTTP状态码->HTTP Status Code
    给所有的input trim去空格
    git clone 使用用户名和密码
    ABA问题
    FIFO、LRU、LFU的含义和原理
    【phpstorm】破解安装
    【windows7】解决IIS 80端口占用问题(亲测)
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5318658.html
Copyright © 2020-2023  润新知