Đề bài
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ụ
Đầ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.
Đầ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.