すべてのチャレンジ
難しい 1件解決済み 正答率100.0%

Find Many Patterns in Text

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

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

例

例 1
入力:
text = "bananas"
patterns = ["ana", "apple", "nas"]

期待される出力:
expected = ["YES", "NO", "YES"]
入力:
std::string text = "bananas";
std::vector<std::string> patterns = {"ana", "apple", "nas"};

期待される出力:
std::vector<std::string> expected = {"YES", "NO", "YES"};
入力:
string text = "bananas";
string[] patterns = new string[] {"ana", "apple", "nas"};

期待される出力:
string[] expected = new string[] {"YES", "NO", "YES"};

解説

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

例 2
入力:
text = "aaaa"
patterns = ["aa", "aaaaa", "aa"]

期待される出力:
expected = ["YES", "NO", "YES"]
入力:
std::string text = "aaaa";
std::vector<std::string> patterns = {"aa", "aaaaa", "aa"};

期待される出力:
std::vector<std::string> expected = {"YES", "NO", "YES"};
入力:
string text = "aaaa";
string[] patterns = new string[] {"aa", "aaaaa", "aa"};

期待される出力:
string[] expected = new string[] {"YES", "NO", "YES"};

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 848 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。