Vous devez vous connecter pour exécuter votre code.

Recherche naïve — première occurrence

É 9.7 — Implémentez la recherche naïve de la première occurrence d'un mot x dans un texte y. La recherche doit s'arrêter dès que le mot est trouvé.

#include <stdio.h> #include <string.h> // Retourne l'indice de la première occurrence de s dans t, ou -1 int naive_first_search(const char *t, const char *s) { size_t n = strlen(t), m = strlen(s); if (m == 0) return 0; for (size_t k = 0; k + m <= n; k++) { size_t j = 0; while (j < m && t[k + j] == s[j]) j++; if (j == m) return (int)k; } return -1; } int main() { int n; scanf("%d", &n); int arr[1000]; for (int i = 0; i < n; i++) scanf("%d", &arr[i]); printf("%d\n", naive_first_search(arr, n)); return 0; }