leetcode-44. Wildcard Matching
生活随笔
收集整理的這篇文章主要介紹了
leetcode-44. Wildcard Matching
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目闡釋:
正則匹配字符串,用程序實現關鍵理解:
正則匹配,動態規劃思想,一個個向后追溯,后面的依賴前面的匹配成功。 正則和待匹配的字符串長度不一,統一到正則字符串的index索引上,每次的字符串index移動,都以匹配到的正則的index為準。 正則由于*?的存在,所以有多種狀態,中間狀態儲存都需要記錄下來。然后以這些狀態為動態的中轉,繼續判斷到最后。 最后正則匹配字符串是否成功的判斷依據,就是正則字符串的最大index,是否出現在遍歷到最后的狀態列表中。錯誤之處:
多處動態變化,導致無法入手,*沒有處理思路,沒有找到匹配成功的條件應用:
正則屬于多條路徑問題,可以推理到 多種渠道的問題,匹配成功當前的才往后推 *相當于無限向后匹配,所以無限循環使用,看能否匹配成功。Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence).The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1:Input:
s = "aa" p = "a" Output: falseExplanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa" p = "*" Output: trueExplanation: '*' matches any sequence.
Example 3:
Input:
s = "cb" p = "?a" Output: falseExplanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input:
s = "adceb" p = "*a*b" Output: trueExplanation: The first '' matches the empty sequence, while the second '' matches the substring "dce".
Example 5:
Input:
s = "acdcb" p = "a*c?b" Output: false class Solution(object):def isMatch(self, s, p):""":type s: str:type p: str:rtype: bool"""transfer = {}index=0for char in p:if char=='*':transfer[index,char]=indexelse:transfer[index,char]=index+1index+=1accept=index# index=0state = {0}for char in s:state_tmp=set()for index in state:for char_prob in [char,'?','*']:index_next=transfer.get((index,char_prob))state_tmp.add(index_next)state=state_tmpreturn accept in stateif __name__=='__main__':s = "acdcb"p = "a*c?b"p = "a**c?d"st=Solution()out=st.isMatch(s,p)print(out)總結
以上是生活随笔為你收集整理的leetcode-44. Wildcard Matching的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ 3259 Wormholes【最
- 下一篇: 验证视图状态MAC失败的解决办法