-
串的模式匹配算法之二:首尾匹配算法
using System;
namespace EasyIndex
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
class Index
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
static void Main(string[] args)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string s="acabaabcaabaabcac";
string m="abaabcac";
int i=0;
int j=0;
while(i<s.Length && j<m.Length)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(s[i]==m[0])//判断两串的第一个元素是否相等
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(s[i+m.Length-1]==m[m.Length-1])//如果头元素相等,再判断尾元素是否相等;
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
i=1;
j=0;
while(i<s.Length && j<m.Length)//如果头尾都相等,再从第二个元素到倒数第二个元素判断;
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(s[i]==m[j])
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
i++;
j++;
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
i=i-j+1;
j=0;
}
}
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
i=i-j+1;
j=0;
}
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
i=i-j+1;
j=0;
}
}
if(j>=m.Length)//说明m是s的一个子串,而且pos是i-m.Lengh+1,因为数组从0开始计数;
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine("m与s中第"+Convert.ToString(i-m.Length+1)+"个元素开始的子串相匹配!");
}
else
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine("m不是s的子串!");
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
-
相关阅读:
JavaScript(ASP)常用代码
用JavaScript + jMail发邮件
SQL语句导入导出大全
C#编程方式执行包的任务
匹配版本号
c# web 页面帮定数据的 7中方式
好书
奇怪的异步调用,那位高手能帮忙看一下?
vb6 调用c# 服务
易犯的错误忘了初始化对象
-
原文地址:https://www.cnblogs.com/gmq/p/515610.html
Copyright © 2020-2023
润新知