字符串匹配方法
介紹兩種字符串匹配方法
1.暴力匹配
母串用s表示,長度為m
子串用p表示,長度為n
時(shí)間復(fù)雜度為:(m-n+1)n
算法:從s串的第一個(gè)字符開始匹配,若匹配,繼續(xù)根據(jù)p向后匹配,若后續(xù)的不匹配,s右移重新匹配p?
2.KMP算法
母串用s表示,長度為m
子串用p表示,長度為n
時(shí)間復(fù)雜度為:預(yù)處理階段m
算法:①計(jì)算next[]數(shù)組 ②字符串匹配
【參考】?
?http://kb.cnblogs.com/page/176818/
?http://www.cnblogs.com/gaochundong/p/string_matching.html
?http://blog.csdn.net/v_july_v/article/details/7041827?
【C語言實(shí)現(xiàn)】?
?1.暴力匹配
#include <stdio.h>#include <string.h>int main(){char *s="ASDFZGasdFZGdfasdFZGsdFZGFZG";char *p="FZG";int i=0,j=0,count=0;int len_s=strlen(s);int len_p=strlen(p);while(i<len_s&&j<len_p){if (s[i]==p[j]){i++;j++;}?else{i=i-j+1;j=0;}if (len_p==j){?printf("%d\n",i-j);//打印匹配成功的起始位置?
count++;//計(jì)算匹配次數(shù)?j=0;}}printf("%d\n",count);//打印匹配次數(shù)return 0;}?
?2.KMP算法?
#include <stdio.h>#include <string.h>int KmpSearch(char* s, char* p, int next[]);void GetNext(char* p,int next[]);int main(){char *s="asfdafASDdfda";char *p="SD";int next[3]={0};GetNext(p,next);KmpSearch(s,p,next);return 0;}int KmpSearch(char* s, char* p, int next[]) ?{ ?int i = 0; ?int j = 0; ?int sLen = strlen(s); ?int pLen = strlen(p); ?while (i < sLen && j < pLen) ?{ ?//①如果j = -1,或者當(dāng)前字符匹配成功(即S[i] == P[j]),都令i++,j++ ? ? ?if (j == -1 || s[i] == p[j]) ?{ ?i++; ?j++; ?} ?else ?{ ?//②如果j != -1,且當(dāng)前字符匹配失敗(即S[i] != P[j]),則令 i 不變,j = next[j] ? ? ?//next[j]即為j所對(duì)應(yīng)的next值 ? ? ? ?j = next[j]; ?} ?} ?if (j == pLen){printf("%d\n",i-j);//打印匹配成功的起始位置?return i - j; ?}else ?return -1; ?}?void GetNext(char* p,int next[]) ?//該函數(shù)為計(jì)算next[]數(shù)組,看不太懂。。。算法暫且先記住吧{ ?int pLen = strlen(p); ?next[0] = -1; ?//第一位數(shù)字置為-1,其余的是最長公共元素右移一位int k = -1; ?int j = 0; ?while (j < pLen - 1) ?{ ?//p[k]表示前綴,p[j]表示后綴 ?if (k == -1 || p[j] == p[k]) ??{ ?++k; ?++j; ?next[j] = k; ?} ?else ??{ ?k = next[k]; ?} ?} ?}?
轉(zhuǎn)載于:https://www.cnblogs.com/kinghero/p/5604415.html
總結(jié)
- 上一篇: DOM 基础 HTML标签 元素 属性
- 下一篇: jQuery基础--样式篇(3)