Khó 0 đã giải Tỷ lệ chấp nhận 0%

Find Many Patterns in Text

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
text = "bananas"
patterns = ["ana", "apple", "nas"]

Kết quả mong đợi:
expected = ["YES", "NO", "YES"]
Đầu vào:
std::string text = "bananas";
std::vector<std::string> patterns = {"ana", "apple", "nas"};

Kết quả mong đợi:
std::vector<std::string> expected = {"YES", "NO", "YES"};
Đầu vào:
string text = "bananas";
string[] patterns = new string[] {"ana", "apple", "nas"};

Kết quả mong đợi:
string[] expected = new string[] {"YES", "NO", "YES"};

Giải thích

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

Ví dụ 2
Đầu vào:
text = "aaaa"
patterns = ["aa", "aaaaa", "aa"]

Kết quả mong đợi:
expected = ["YES", "NO", "YES"]
Đầu vào:
std::string text = "aaaa";
std::vector<std::string> patterns = {"aa", "aaaaa", "aa"};

Kết quả mong đợi:
std::vector<std::string> expected = {"YES", "NO", "YES"};
Đầu vào:
string text = "aaaa";
string[] patterns = new string[] {"aa", "aaaaa", "aa"};

Kết quả mong đợi:
string[] expected = new string[] {"YES", "NO", "YES"};

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.