Ana amfani da algorithm ɗin bincike na kirtani don nemo abubuwan da suka faru na ƙayyadaddun tsari(substring) a cikin babban rubutu(kirtani). Wannan algorithm yana taka muhimmiyar rawa wajen sarrafa rubutu, bincike, da ayyukan magudi.
Yadda Ake Aiki
- Fara da rubutu(kirtani) da tsari(ƙarshen igiya) don nema.
- Maimaita ta cikin rubutun harafi ɗaya a lokaci guda.
- Ga kowane harafi a cikin rubutun, kwatanta shi da harafin farko na ƙirar.
- Idan akwai wasa, duba idan haruffan da ke gaba kuma sun dace da tsarin.
- Idan tsarin ya dace sosai, yi rikodin matsayin farawa na wasan.
- Ci gaba da neman tsari a cikin rubutun.
Misali
Yi la'akari da rubutu: "ababcababcabcabc" Kuma tsari: "abc"
- Fara a matsayi 0. Kwatanta "a" tare da harafin farko "a" a cikin tsari.
- An samo daidai, matsa zuwa haruffa na gaba: "b" tare da "b", da "a" tare da "c".
- Ci gaba da daidaitawa: "b" tare da "a", "a" tare da "b", da "b" tare da "c".
- Wasan ya gaza a matsayi na 2.
- Fara sake a matsayi na 3. Kwatanta "a" tare da harafin farko "a" a cikin tsari.
- Wasan nasara: "a" tare da "a", "b" tare da "b", da "c" tare da "c".
- Matsayin rikodin 3.
Ana samun samfurin "abc" a matsayi na 0, 6, da 9.
Misali Code a C++
#include <iostream>
#include <string>
#include <vector>
std::vector<int> stringSearch(const std::string& text, const std::string& pattern) {
std::vector<int> positions;
for(int i = 0; i <= text.length()- pattern.length(); ++i) {
int j = 0;
while(j < pattern.length() && text[i + j] == pattern[j]) {
++j;
}
if(j == pattern.length()) {
positions.push_back(i);
}
}
return positions;
}
int main() {
std::string text = "ababcababcabcabc";
std::string pattern = "abc";
std::vector<int> result = stringSearch(text, pattern);
std::cout << "Pattern found at positions: ";
for(int pos: result) {
std::cout << pos << ";
}
std::cout << std::endl;
return 0;
}
A cikin wannan misali, stringSearch
ana amfani da aikin don nemo abubuwan da suka faru na tsarin "abc" a cikin rubutun "ababcababcabcabc". Sakamakon zai zama vector mai kunshe da wuraren farawa na matches.