forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NaiveStringSearch.cs
43 lines (40 loc) · 1.44 KB
/
NaiveStringSearch.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System.Collections.Generic;
// Implements the traditional naive string matching algorithm in C# for TheAlgorithms/C-Sharp.
namespace Algorithms.Strings
{
/// <summary>
/// Implements the traditional naive string matching algorithm in C#.
/// </summary>
public static class NaiveStringSearch
{
/// <summary>
/// NaiveSearch(Content, Pattern) will return an array containing each index of Content in which Pattern appears.
/// Cost: O(n*m).
/// </summary>
/// <param name="content">The text body across which to search for a given pattern.</param>
/// <param name="pattern">The pattern against which to check the given text body.</param>
/// <returns>Array containing each index of Content in which Pattern appears.</returns>
public static int[] NaiveSearch(string content, string pattern)
{
var m = pattern.Length;
var n = content.Length;
List<int> indices = new();
for (var e = 0; e <= n - m; e++)
{
int j;
for (j = 0; j < m; j++)
{
if (content[e + j] != pattern[j])
{
break;
}
}
if (j == m)
{
indices.Add(e);
}
}
return indices.ToArray();
}
}
}