數據結構清華大學出版社,4.3節ios
基本思想:主串S, 模式串T, 求模式串在主串中某一個pos位置開始查找,返回其出現的位置。用i 和 j分別指示指向當前主串S和模式串T元素的下標,從0開始。數據結構
首先將主串S的pos位置元素和模式串0位置元素開始比較,若是相等則 i 和 j 都加1,不然i回溯,j回到0。i回溯到的值爲i - j + 1,課本上是i - j + 2,由於課本用的下標是從1開始,而咱們這裏是從0開始。 直到i 或 j 超過了主串S 或 模式串T的最後一個元素位置。spa
代碼以下:code
1 // StringMatch.cpp : 定義控制檯應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 using namespace std; 7 8 //strMain爲主串 9 //strMatch爲模式串 10 //返回模式串在pos位置開始查找的出現位置 11 //pos最小爲0,最大爲主串長度 - 模式串長度 12 //eg. strMain == "hello" 13 //strMatch == "ll", 則pos最大爲5 - 2 == 3 14 int StringMatch(const TCHAR* strMain, const TCHAR* strMatch, size_t pos) 15 { 16 size_t nMain = _tcslen(strMain); 17 size_t nMatch = _tcslen(strMatch); 18 19 if (NULL == strMain || NULL == strMatch //輸入爲空 20 || pos > (nMain - 1) //起始位置超過主串最後一個位置 21 || pos > (nMain - nMatch) //起始位置超過一個合理的位置 22 || nMatch > nMain //模式串長度大於主串 23 ) 24 { 25 return -1; 26 } 27 28 size_t i = pos; //主串的比較的起始位置 29 size_t j = 0; //模式串比較的起始位置 30 31 int index = -1; //返回的位置; 32 33 while ( i < nMain && j < nMatch ) 34 { 35 if (strMain[i] == strMatch[j]) 36 { 37 ++i; ++j; 38 } 39 //回溯 40 else 41 { 42 j = 0; 43 i = i - j + 1; 44 } 45 } 46 47 if (j >= nMatch) 48 { 49 index = i - nMatch; 50 } 51 else 52 { 53 index = -1; 54 } 55 56 return index; 57 58 } 59 60 61 int _tmain(int argc, _TCHAR* argv[]) 62 { 63 const TCHAR* lpMain = _T("helloworld"); 64 const TCHAR* lpMatch = _T("oworl"); 65 size_t pos = 3; 66 67 68 wcout<<"模式串"<<lpMatch<<"在主串"<<lpMain<<"中"<<pos<<"位置開始查找,出現的位置是"<<StringMatch(lpMain, lpMatch, pos)<<endl; 69 70 return 0; 71 }
運行結果以下:blog