Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++ Program: Repeated String Search (Naive Algorithm)


การค้นหา Pattern ใน Text เดียวกันหลายครั้ง (Repeated Search) หาก Text คงที่ แต่ Pattern เปลี่ยนบ่อย ควรสร้าง Index/Data Structure ไว้ล่วงหน้า เช่น Suffix Array, Suffix Tree, Suffix Automaton

Naive Algorithm (Baseline)

สำหรับ Single Search โดยไม่มี Preprocessing

Complexity

  • Time: O(N × M) Worst Case (N = Text Length, M = Pattern Length)
  • Space: O(1)

โค้ด C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector naiveSearch(const string& text, const string& pattern) {
    vector positions;
    int n = text.length(), m = pattern.length();
    
    if (m == 0 || n < m) return positions;
    
    for (int i = 0; i <= n - m; i++) {
        bool match = true;
        for (int j = 0; j < m; j++) {
            if (text[i + j] != pattern[j]) {
                match = false;
                break;
            }
        }
        if (match) positions.push_back(i);
    }
    return positions;
}

int main() {
    string text, pattern;
    cout << "Enter text: "; getline(cin, text);
    cout << "Enter pattern: "; getline(cin, pattern);
    
    auto matches = naiveSearch(text, pattern);
    
    if (matches.empty()) {
        cout << "No match found\n";
    } else {
        for (int pos : matches) {
            cout << "Pattern found at position: " << pos << "\n";
        }
        cout << "Total matches: " << matches.size() << "\n";
    }
    return 0;
}

Output Example

Enter text: thisistutorialspoint.thisisac++program
Enter pattern: is
Pattern found at position: 2
Pattern found at position: 4
Pattern found at position: 23
Pattern found at position: 25
Total matches: 4

Data Structures สำหรับ Repeated Search (Text คงที่)

1. Suffix Array + LCP Array

  • Build: O(N log N) หรือ O(N) (SA-IS)
  • Search: O(M log N) Binary Search
  • Space: O(N)

2. Suffix Tree (Ukkonen's Algorithm)