-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNaivePatternSearch.cs
More file actions
35 lines (27 loc) · 994 Bytes
/
NaivePatternSearch.cs
File metadata and controls
35 lines (27 loc) · 994 Bytes
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
namespace AlgorithmsAndDataStructures.Algorithms.Strings.Search;
public class NaivePatternSearch : IStringPatternSearchAlgorithm
{
public int Search(string input, string pattern)
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(pattern)) return -1;
const int negativeResult = -1;
if (pattern.Length > input.Length) return negativeResult;
for (var i = 0; i <= input.Length - pattern.Length; i++)
if (input[i] == pattern[0])
{
var originalPosition = i + 1;
var isMatch = true;
for (var j = 1; j < pattern.Length; j++)
{
if (input[originalPosition] != pattern[j])
{
isMatch = false;
break;
}
originalPosition++;
}
if (isMatch) return i;
}
return negativeResult;
}
}