您的位置:首页 > 其它

LeetCode 44. Wildcard Matching

2016-11-13 15:55 429 查看

Problem Statement

(Source) 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).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false


Tags:
Dynamic Programming
,
Backtracking
,
Greedy
,
String
.

Solution 1 - Backtracking

class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
n, m = len(s), len(p)
i, j, next_match, star = 0, 0, 0, -1
while i < n:
if j < m and (s[i] == p[j] or p[j] == '?'):
i, j = i+1, j+1
elif j < m and p[j] == '*':
star = j
j += 1
next_match = i
elif star != -1:
next_match += 1
i = next_match
j = star + 1
else:
return False
while j < m and p[j] == '*':
j += 1

return j == m


Reference:

(1) https://discuss.leetcode.com/topic/3040/linear-runtime-and-constant-space-solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: