KMP算法求目标串是否是源串的子串

// -------------------------------------
// KMP算法求目标串是否是源串的子串
// 是 返回position
// 否 返回-1
// -------------------------------------


#include <iostream>
#include <string> 
using namespace std;

void GetNext(string s, int next[], int length) {
 int i = 0;
 int j = -1;
 next[0] = -1;
 while (i < length) {
  if (j == -1 || s[i] == s[j]) {
   i++;
   j++;
   next[i] = j;
  }
  else {
   j = next[j];
  }
 }
}


int IsSubString_Kmp(string source, string target) {
 int pos = -1;
 int sLen = source.length();
 int tLen = target.length();
 int i = 0, j = 0;
 int *next = new int[tLen];
 GetNext(target,next, tLen);

 while (i < sLen&&j < tLen) {
  if (j == -1|| target[j] == source[i]) {
   i++;
   j++;
  }
  else {
   j = next[j];
  }
 }

 if (j == tLen)
  pos = i - tLen;
 return pos;
}

int main() {
 string s = "adsadsadadss", t = "adsada";
 cout << IsSubString_Kmp(s, t) << endl;

 system("pause");
 return 0;
}

posted @ 2017-02-22 19:42  codingtao  阅读(399)  评论(0编辑  收藏  举报