150強訪談中等

正規表示式匹配

「正規表示式符合」問題的詳細指南和 Python 實作。

問題陳述

中等

給定輸入字串 s 和模式 p,實現支援“.”的正規表示式匹配和“*”,其中:

- '.'符合任何單一字元。

- '*' 符合零個或多個前面的元素。

匹配應覆蓋整個輸入字串(而不是部分)。

寫一個函數 isMatch(s: str, p: str) -> bool

約束條件
  • 1 <= len(s) <= 20
  • 1 <= len(p) <= 20
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, '.', and '*'.
  • It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.

範例

Example 1
Input
s = "aa", p = "a"
Output
False
Explanation

"a" does not match the entire string "aa".

Example 2
Input
s = "aa", p = "a*"
Output
True
Explanation

'*' repeats the preceding 'a' once to match "aa".

Example 3
Input
s = "ab", p = ".*"
Output
True
Explanation

".*" matches zero or more of any character.

Need a Hint?
考慮使用 2D DP 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。