Tất cả thử thách
Khó 1 người đã giải Tỷ lệ chấp nhận 50.0%

Minimum Window Substring

Find the shortest piece of text containing all required characters.

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

  • Grow and shrink a window over text
  • Track required character counts
  • Find the shortest valid window

Đề bài

Xem bản dịch

Find the shortest contiguous substring of text that contains every character of pattern, including repeats. If several are equally short, return the leftmost.

Implement min_window(text, pattern).

Input

text: The text to search. pattern: The characters that must appear.

Output

Return the shortest window, or an empty string if none exists.

Ràng buộc

1 ≤ length of text, pattern ≤ 100,000 (ASCII)

Ví dụ

Ví dụ 1
Đầu vào:
text = "ADOBECODEBANC"
pattern = "ABC"

Kết quả mong đợi:
expected = "BANC"
Đầu vào:
std::string text = "ADOBECODEBANC";
std::string pattern = "ABC";

Kết quả mong đợi:
std::string expected = "BANC";
Đầu vào:
string text = "ADOBECODEBANC";
string pattern = "ABC";

Kết quả mong đợi:
string expected = "BANC";

Giải thích

"BANC" contains A, B and C and nothing shorter does.

Ví dụ 2
Đầu vào:
text = "a"
pattern = "aa"

Kết quả mong đợi:
expected = ""
Đầu vào:
std::string text = "a";
std::string pattern = "aa";

Kết quả mong đợi:
std::string expected = "";
Đầu vào:
string text = "a";
string pattern = "aa";

Kết quả mong đợi:
string expected = "";

Giải thích

Two a's are needed but the text has only one: "".

Hướng tiếp cận

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

Gợi ý 1

The window must cover all needed character counts, not just distinct characters.

Gợi ý 2

Expand until valid, then shrink from the left to remove unnecessary characters while staying valid.

Gợi ý 3

If multiple windows share the same minimum length, keep the earliest one when updating your best answer.

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

O(n) time, O(1) 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.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 Н"Никита "Programmer" Python 835 ms - 5/5 Xem code

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

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.