生活随笔
收集整理的這篇文章主要介紹了
时间复杂度为m+n,的一种模式匹配,适合子串不是很长的匹配
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
子串長度應該小于?(int類型表示最大值)/256
//自己想出來的模式匹配算法,記得在藍橋杯比賽中用過,方法應該早就存在了,我也不知道叫什么#include<stdio.h>
#include<string.h>
#include<malloc.h>int KMP_ADD(char * s ,char * t ,int pos) ;//返回pos之后的子串t在主串s中第一次出現的位置,不存在返回-1int main (){int i ;i = KMP_ADD("1234123","123" ,0);printf("%d" , i) ;return 0;
}int KMP_ADD(char * s ,char * t ,int pos){int s_l = strlen(s) ;int t_l = strlen (t) ;// printf("%d %d \n",s_l,t_l);int i , j , t_sum,s_sum ;char *sc ;sc = (char*)malloc ((t_l+1)*sizeof(char)) ;if (sc == NULL)return -1 ;if (s_l-pos < t_l)return -1;for( i =0 ,t_sum = 0; i<t_l ; i ++){t_sum+=t[i] ;}for (i=pos,s_sum=0 ; i<s_l ; i++){s_sum+=s[i] ;if (i>=pos+t_l-1){if (s_sum == t_sum){strcpy(sc,&s[i-t_l+1]);sc[t_l] = '\0';if (!strcmp(sc,t)){free(sc);return i-t_l+1;}else{s_sum -= s[i-t_l+1];}}else{s_sum -= s[i-t_l+1];}}}free(sc);return -1;
}
總結
以上是生活随笔為你收集整理的时间复杂度为m+n,的一种模式匹配,适合子串不是很长的匹配的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。