The string being searched is called the main string, and the strings to be searched are called pattern strings. The basic idea of naive pattern matching algorithm:
Starts each character of the main string as a substring and matches the pattern string. Cycle through the main string, and each character starts with a small loop of the length of the pattern string until the match succeeds or all traversal is complete.
The code implementation is simple:
intSTRSTR (Char*haystack,Char*needle) { for(inti =0; ; ++i) { for(intj =0; ; ++J) {if(!needle[j])returnIif(!haystack[i + j])return-1;if(Needle[j]! = Haystack[i + j]) Break; } } }
The time complexity analysis of the naïve pattern matching algorithm is as follows:
Case |
Complexity of Time |
Note |
Best case |
O (1) |
The match was successful at first. |
Worst case scenario |
O ((n-m+1) *m) |
Each unsuccessful match occurs at the last character of the pattern string. |
Average situation |
O (N+M) |
According to the equal probability principle, the average is (n+m)/2-time lookup. |
Note: where n is the main string length, M is the pattern string length.
One of the string pattern matching algorithms: Naïve pattern matching algorithm