難しい 1件解決済み 正答率50.0%

Minimum Window Substring

Find the shortest piece of text containing all required characters.

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

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

問題

翻訳を表示

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)

例

例 1
入力:
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.

例 2
入力:
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つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

O(n) time, O(1) extra space

参考資料

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

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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