โจทย์
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.
เงื่อนไข
1 ≤ length of text, pattern ≤ 100,000 (ASCII)
ตัวอย่าง
อินพุต:
text = "ADOBECODEBANC"
pattern = "ABC"
ผลลัพธ์ที่คาดหวัง:
expected = "BANC"
อินพุต:
std::string text = "ADOBECODEBANC";
std::string pattern = "ABC";
ผลลัพธ์ที่คาดหวัง:
std::string expected = "BANC";
อินพุต:
string text = "ADOBECODEBANC";
string pattern = "ABC";
ผลลัพธ์ที่คาดหวัง:
string expected = "BANC";
คำอธิบาย
"BANC" contains A, B and C and nothing shorter does.
อินพุต:
text = "a"
pattern = "aa"
ผลลัพธ์ที่คาดหวัง:
expected = ""
อินพุต:
std::string text = "a";
std::string pattern = "aa";
ผลลัพธ์ที่คาดหวัง:
std::string expected = "";
อินพุต:
string text = "a";
string pattern = "aa";
ผลลัพธ์ที่คาดหวัง:
string expected = "";
คำอธิบาย
Two a's are needed but the text has only one: "".
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
window ต้องครอบคลุมจำนวนอักขระที่ต้องการทั้งหมด ไม่ใช่แค่ชนิดที่ต่างกัน
คำใบ้ 2
ขยายจน valid แล้วค่อยหดจากซ้ายเพื่อตัดอักขระที่ไม่จำเป็นออกในขณะที่ยัง valid อยู่
คำใบ้ 3
ถ้ามีหลาย window ที่สั้นเท่ากัน ให้เก็บอันที่เริ่มก่อนเมื่ออัปเดตคำตอบที่ดีที่สุด
ความซับซ้อนที่คาดหวัง
เวลา O(n), หน่วยความจำเพิ่ม O(1)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน