नैव पैटर्न खोज अन्य पैटर्न खोज एल्गोरिदम में सबसे सरल विधि है। यह मुख्य स्ट्रिंग के सभी कैरेक्टर की पैटर्न से जांच करता है। यह एल्गोरिदम छोटे टेक्स्ट के लिए सहायक है। इसे किसी प्री-प्रोसेसिंग चरण की आवश्यकता नहीं होती। हम स्ट्रिंग की एक बार जांच करके सबस्ट्रिंग ढूंढ सकते हैं। यह ऑपरेशन करने के लिए अतिरिक्त स्पेस भी नहीं लेता।
नैव पैटर्न खोज विधि की समय जटिलता O(m*n) है। m पैटर्न का आकार है और n मुख्य स्ट्रिंग का आकार है।
इनपुट और आउटपुट
इनपुट: मुख्य स्ट्रिंग: "ABAAABCDBBABCDDEBCABC", पैटर्न: "ABC" आउटपुट: पैटर्न स्थान पर मिला: 4 पैटर्न स्थान पर मिला: 10 पैटर्न स्थान पर मिला: 18
एल्गोरिदम
naivePatternSearch(pattern, text)
इनपुट - टेक्स्ट और पैटर्न
आउटपुट - स्थान, जहां पैटर्न टेक्स्ट में मौजूद हैं
Begin
patLen := pattern Size
strLen := string size
for i := 0 to (strLen - patLen), do
for j := 0 to patLen, do
if text[i+j] ≠ pattern[j], then
break the loop
done
if j == patLen, then
display the position i, as there pattern found
done
End
उदाहरण
#include<iostream> using namespace std; void naivePatternSearch(string mainString, string pattern, int array[], int *index) { int patLen = pattern.size(); int strLen = mainString.size(); for(int i = 0; i<=(strLen - patLen); i++) { int j; for(j = 0; j
आउटपुट
Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18