这是使用类构造和队列来查找子数组的确切索引的答案。
namespace Alogrithms
{
public class ArraySearch
{
int[] pattern;
Queue<int> indices = new Queue<int>();
int[] source;
public ArraySearch( int[] pattern, int[] source)
{
this.source = source;
this.pattern = pattern;
}
public int[] Pattern
{
get { return pattern; }
private set { pattern = value; }
}
public Queue<int> Indices
{
get { return indices; }
private set { indices = value; }
}
public int SearchForSubArray(int patternIndexPtr,int sourceIndexPtr, ref int[] source)
{
int end = source.Length;
if(patternIndexPtr >= pattern.Length || sourceIndexPtr >= end )
return patternIndexPtr;
if(pattern[patternIndexPtr] == source[sourceIndexPtr])
{
indices.Enqueue(sourceIndexPtr);
return SearchForSubArray(patternIndexPtr + 1,sourceIndexPtr+1, ref source);
}
else
{
indices.Clear();
patternIndexPtr = 0;
return SearchForSubArray(patternIndexPtr, sourceIndexPtr + 1, ref source);
}
}
}
}
类用法:
int [] randomArray = new int[]{9,8,9,6,5,6,4,7,8,5,4,5,6,3,2,1,3,5,6,5,5,9,6,3,4,5,7,6,8,9,6,7,8,9,9,9,8,2,1,3,5,6,5,5,9,6,3,4,5,7,6,8,9,9,9,9,8};
int[] pattern = new int[] { 6, 7, 8 };
ArraySearch sequence = new ArraySearch(randomArray,pattern);
int found = sequence.SearchForSubArray(0, 0, ref randomArray);
Console.WriteLine("found : " + found);
Console.WriteLine("Pattern is : " + String.Join(",", sequence.Pattern));
foreach(int point in sequence.Indices)
{
Console.WriteLine(point);
}
if ( sequence.Indices.Count == 0 )
{
Console.WriteLine("Sequence not found.");
}
Console.ReadLine();