1 / 7

所有匹配问题

所有匹配问题. 030402318. 问题描述: 试修改 KMP 算法 Match ,使其能找到模式串 t 在主串 s 中的所有匹配位置。 编程任务: 给定模式串 t 和主串 s ,编程计算 t 在主串 s 中的所有匹配位置。 数据输入: 由文件 input.txt 给出输入数据。第 1 行是主串 s ;第 2 行是模式串 t 。. 结果输出 :. 将计算出的模式串 t 在主串 s 中的所有匹配位置输出到文件 output.txt 。 输入文件示例 输出文件示例

bandele
Download Presentation

所有匹配问题

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 所有匹配问题 030402318

  2. 问题描述: • 试修改KMP算法Match,使其能找到模式串t在主串 s中的所有匹配位置。 • 编程任务: • 给定模式串t和主串s,编程计算t在主串 s中的所有匹配位置。 • 数据输入: • 由文件input.txt给出输入数据。第 1 行是主串s;第 2 行是模式串t。

  3. 结果输出: • 将计算出的模式串t在主串s中的所有匹配位置输出到文件 output.txt。 • 输入文件示例 输出文件示例 • input.txt output.txt • aabaabaaba 1 4 7 • aaba

  4. 解题思路: • 修改KMP算法如下:幻灯片 5

  5. 循环条件是i<=n • void String::Matchall(String& t) • { • int i=1,j=0,count=0; • int n=Length(),m=t.Length(); • t.ModifiedPrefix(); • while(i<=n) • { • if(str[i-1]==t.str[j]) • { • i++; • j++; • } • else • if(j==0) • i++; • else • j=t.pre[j]; • if(j==m) • { • out<<i-m<<' '; • count++; • } • } • if(count==0)//找不到匹配模式串 • cout<<" "; • } 找到一个匹配

  6. 示例:主串s: aabaabaaba模式串t: aaba i=5 j=4时,输出i-m=1.然后j=pre[4]=1. j=4 i=5 j=pre[4]=1,主串中i=5不变,模式串向右滑至j=1位置。 j=1

  7. i=8 j=4 此时j=pre[4]=1 …… 接下来,i不变,模式串仍然向右滑至j=pre[4]=1处,继续匹配,直到i>n循环结束,则就找到所有的匹配位置。 ★算法时间复杂性分析: 显然是Ο(n+m)的时间。

More Related