title: 【LeetCode】0044. Wildcard Matching
date: 2018-12-20
is_modified: false
disqus: cynthiahackmd
categories:
Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
.
The matching should cover the entire input string (not partial).
Note:
s
could be empty and contains only lowercase lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like?
or*
.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Related Topics: String
、Backtracking
、Dynamic Programming
、Greedy
有點像是第十題的 Regular Expression Matching,不過符號的意義不太一樣,這邊使用的 ?
表示一個萬用字元, *
則是表示多個萬用字元。
跟 Regular Expression 相比最大的差異應該是 *
的用法。在 Regular Expression 中 *
不可能單獨存在,必定會跟在某個字元後面,在產生 subpattern 時要特別注意;但在這題中 *
可以單獨存在,subpatter 應該只有 pattern 或 pattern[1:] 兩種。
*
?
與 *
的情況)
*
一樣多加了參數暫存比較結果,節省呼叫次數。不過按照上面那個邏輯去寫在遇到這個 testcase 時會 Memory Limit Exceeded,所以修改了第二個判斷式的邏輯,判斷 pattern 扣除掉 *
長度:
*
長度為 0,則回傳 True
*
,因此不用管 string 內容是什麼一定會匹配。*
長度大於 string 的長度,則回傳 False
*
全用來匹配空字串,仍會有部份 pattern 無法匹配上 string,因為除*
外的 pattern 符號都必須匹配一個字元,但目前 pattern 比 string 還長…總算可以過了,但說實話效能不是很好,跑出了 1096 ms、40.91 %的成績,還有非常大的改進空間。
原本是在找 Dynamic Programming 的解法,但連續找到兩篇說用 DP 會 TLE,說要改用雙指標回溯,所以我決定也來寫寫看:
?
,但排除為 *
的情況),兩個指標皆向後移動*
,則 pattern 指標向後移動,並記下目前指標位置(last_s_index 與 last_p_index)
*
匹配的是空字元的情況,向後進行匹配,*
匹配空字元狀況下,無法完成整句匹配,因此所記錄的位置,且 last_s_index 加一
*
,因此可以不再考慮*
外的字元
效能好上不少,136 ms、 83.93%
是說看標籤應該還可以用 Dynamic Programming 跟 Greedy Algorithm 來解題,先欠著回頭再來研究 XD
本文作者: 辛西亞.Cynthia
本文連結: 辛西亞的技能樹 / hackmd 版本
版權聲明: 部落格中所有文章,均採用 姓名標示-非商業性-相同方式分享 4.0 國際 (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!