源码:
//模式匹配算法:时间复杂度(M+N)
public static Hashtable getMatch(Hashtable hsMatch, string condition)//hsMatch:待匹配的原项(key:唯一标示原项,value:待匹配的值);condition为待匹配的目标项;返回匹配的集合
{
char[] temp = condition.ToCharArray();
int[] next = new int[condition.Length];
getNextVal(temp, ref next);
char[] value;
Hashtable matchHS = new Hashtable();
foreach (DictionaryEntry dict in hsMatch)
{
value = dict.Value.ToString().ToCharArray();
int k = 0, i = 0;
//时间复杂度(M+N):M:表示目标字符的长度;N:表示待匹配字符串的长度
while (k < temp.Length && i < value.Length)
{
if (value[i] == temp[k])
{
k++;
i++;
}
else
{
k = next[k];
if (k == -1)
{
k = 0;
i++;
}
}
}
//匹配成功时保存到返回的hashTable
if (k == temp.Length)
{
matchHS.Add(dict.Key, dict.Value);
}
}
return matchHS;
}
//获取字符串的模式值
static void getNextVal(char[] temp, ref int[] next)
{
// 求模式串temp的next函数值并存入数组 next。
int j = 0, k = -1;
next[0] = -1;
while (j < temp.Length - 1)
{
if (k == -1 || temp[j] == temp[k])
{
++j; ++k;
if (temp[j] != temp[k])
next[j] = k;
else
next[j] = next[k];
}// if
else
k = next[k];
}
}