44 Wild card Matching
生活随笔
收集整理的這篇文章主要介紹了
44 Wild card Matching
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
leetcode 44題,題目大意是兩個(gè)字符串s,p,s是原字符串,p是匹配字符串.匹配字符串中*可以代替任意長(zhǎng)度字符串(包括空字符串);?可以視作任意單個(gè)字符串,下面是一些示例
Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2:Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence. Example 3:Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4:Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5:Input: s = "acdcb" p = "a*c?b" Output: false采用的方法毫無(wú)疑問(wèn)就是動(dòng)態(tài)規(guī)劃,(i,j)代表了s前i個(gè)字符和p前j個(gè)字符是否匹配,我一開(kāi)始用的是字典:
class Solution:def isMatch(self, s, p):""":type s: str:type p: str:rtype: bool"""dict_mn = {}m = len(s)n = len(p)dict_mn[(0,0)] = Truefor i in range(1, m+1):dict_mn[(i, 0)] = Falsefor j in range(1, n+1):# for i in range(0, m):pj = p[j-1]if pj == "?":for i in range(0, m+1):dict_mn[(i, j)] = dict_mn.get((i-1, j-1), False)elif pj == "*":for i in range(0, m+1):dict_mn[(i, j)] = dict_mn[(i, j-1)] or dict_mn.get((i-1, j), False)else:for i in range(0, m+1):dict_mn[(i, j)] = dict_mn.get((i-1, j-1), False) and s[i-1] == p[j-1]return dict_mn[(m, n)]但是提示說(shuō)內(nèi)存不足
class Solution:def isMatch(self, s, p):""":type s: str:type p: str:rtype: bool"""m = len(s)n = len(p)dp = [[None for _ in range(n+1)] for _ in range(m+1)]dp[0][0] = Truefor i in range(1, m+1):dp[i][0] = Falsefor j in range(1, n+1):dp[0][j] = dp[0][j-1] and p[j-1] == "*"for j in range(1, n+1):for i in range(1, m+1):pj = p[j-1]if pj == "?":dp[i][j] = dp[i-1][j-1]elif pj == "*":dp[i][j] = dp[i][j-1] or dp[i-1][j]else:dp[i][j] = dp[i-1][j-1] and s[i-1] == p[j-1]return dp[m][n]這下就沒(méi)問(wèn)題了,看見(jiàn)一個(gè)很有意思的解法:
class Solution:def isMatch(self, s, p):""":type s: str:type p: str:rtype: bool"""if len(p) == 0:return len(s) == 0i, j, match_s, star_p = 0, 0, -1, -1while i < len(s):if j < len(p) and (s[i] == p[j] or p[j] == '?'):i += 1j += 1elif j < len(p) and p[j] == '*':match_s, star_p = i, jj += 1elif star_p >= 0:i, j = match_s + 1, star_p + 1match_s += 1else:return Falsewhile j < len(p) and p[j] == '*':j += 1return j == len(p)用了兩個(gè)變量存儲(chǔ)前面的匹配數(shù)量,反復(fù)迭代,很有想法,如果p中出現(xiàn)兩個(gè)*號(hào),那么前面的匹配或者是后面的匹配并沒(méi)有結(jié)果上區(qū)別.
轉(zhuǎn)載于:https://www.cnblogs.com/mangmangbiluo/p/10148895.html
總結(jié)
以上是生活随笔為你收集整理的44 Wild card Matching的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Editplus的扩展程序的删除
- 下一篇: 火车进栈