【算法与数据结构】字符串模式匹配

数据结构清华大学出版社,4.3节

 

基本思想:主串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的最后一个元素位置。

代码如下:

 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 }

 

运行结果如下:

 

  

 

 

 

转载于:https://my.oschina.net/u/926461/blog/350917

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值