Torna alle sfide
Difficile 0 risolte 0% di accettazione

Find Many Patterns in Text

For each requested pattern, decide whether it appears as a contiguous substring anywhere in the shared text.

Cosa imparerai

  • Check many patterns against one text quickly
  • Preprocess text or patterns for fast lookups
  • Compare naive search with indexed search

Problema

Mostra traduzione

For each requested pattern, decide whether it appears as a contiguous substring anywhere in the shared text. Patterns may overlap and may repeat. Return results in the original query order. The limits require an approach that can handle many patterns efficiently.

Implement find_many_patterns(text, patterns).

Input

text: The text searched by every query.

patterns: The patterns, in query order.

Output

Return YES for each occurring pattern and NO for each absent one.

Vincoli

1…100,000 text characters. 1…100,000 nonempty patterns, with total length at most 500,000. All characters are lowercase a–z.

Esempi

Esempio 1
Input:
text = "bananas"
patterns = ["ana", "apple", "nas"]

Output atteso:
expected = ["YES", "NO", "YES"]
Input:
std::string text = "bananas";
std::vector<std::string> patterns = {"ana", "apple", "nas"};

Output atteso:
std::vector<std::string> expected = {"YES", "NO", "YES"};
Input:
string text = "bananas";
string[] patterns = new string[] {"ana", "apple", "nas"};

Output atteso:
string[] expected = new string[] {"YES", "NO", "YES"};

Spiegazione

Ana appears starting at position 2 and nas at position 5 (positions start at 1 here). Apple never appears.

Esempio 2
Input:
text = "aaaa"
patterns = ["aa", "aaaaa", "aa"]

Output atteso:
expected = ["YES", "NO", "YES"]
Input:
std::string text = "aaaa";
std::vector<std::string> patterns = {"aa", "aaaaa", "aa"};

Output atteso:
std::vector<std::string> expected = {"YES", "NO", "YES"};
Input:
string text = "aaaa";
string[] patterns = new string[] {"aa", "aaaaa", "aa"};

Output atteso:
string[] expected = new string[] {"YES", "NO", "YES"};

Spiegazione

Aa occurs despite overlapping matches. Five a characters cannot fit in a four-character text. The repeated aa query receives the same answer.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Many patterns can share work, so avoid searching the text separately for each query.

Suggerimento 2

Build one structure that stores all patterns and scan the text once, advancing matches as characters arrive.

Suggerimento 3

Be careful to report repeated patterns in query order, and let overlapping matches count independently.

Complessità attesa

O(text length + total pattern length) time, O(total pattern length) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.