zoukankan      html  css  js  c++  java
  • 字符串匹配算法

    字符串匹配算法有非常多种,最为经常使用的有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-------------------------------------//




  • 相关阅读:
    查找具有特定属性的元素 (XPath-LINQ to XML)
    Docker环境中部署DzzOffice 1.2.5.2
    如何使用DockerHub官方的mysql镜像
    以Tomcat+Mysql为例,实现Docker多容器连接
    基于Ubuntu 14.04构建mysql5.6 Docker镜像
    如何让Docker容器随宿主机的启动而自动启动
    Docker 常用命令
    基于Ubuntu 14.04构建tomcat7镜像
    Dockerfile的书写规则及指令使用方法
    Ubuntu14.04 安装Oracle JDK
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5318658.html
Copyright © 2011-2022 走看看