Interview Question
Country: United States
static int CountInstance(string word, string pattern)
{
int c = 0;
int m = 0;
foreach (char x in pattern)
{
if (x == pattern[c])
{
c++;
if (c == pattern.Length)
{
c = 0;
m++;
}
}
else
c = 0;
}
return m;
}
string word = Console.ReadLine();
string pattern = Console.ReadLine();
char[] wordarr = word.ToCharArray();
char[] pattarr = pattern.ToCharArray();
int j=0, cnt=0,cntptrnmatch=0;
for (int i = 1; i < word.Length - 1; i++)
{
if (wordarr[i] == pattarr[j])
{
j++;
}
if (j == pattarr.Length)
{
cntptrnmatch++;
j = 0;
}
}
Console.WriteLine("Pattern match times {0}" + cntptrnmatch);
Console.ReadLine();
Knuth–Morris–Pratt algorithm.
- Cerberuz October 16, 2012