Hard-题目51:44. Wildcard Matching

题目原文:
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
题目大意:
实现含有通配符的正则匹配。
题目分析:
这次不能用java的matches函数水过去,就参考一下discuss中大神的解法吧!
众所周知正则匹配默认是贪婪匹配,所以本题也跟贪心有关系。
原文:
Loop
keep two pointers in S and P here i and j
if S[i] == P[j] or P[j] == ‘?’ we keep moving
if ‘*’ exist in P then we mark the position in P as star and mark position in s as s_star
Loop over s until S[i] == P[star + 1] otherwise False
理解如下:两个指针i和j分别从s和p开始,如果s[i]==p[j]或者p[j]==’?’则I,j同时往右推,如果p[j]是’*’,那么记录下当前I,j的位置分别为sstar和star,然后令j指向star+1,sstar一直向后推,直到新的s[i]==p[j]||p[j]==’?’出现(举例:s=”aaaaaaaaaaaaaaaabbbbbb”,t=”a*b*,遇到第一个*的时候j指向b,i如果是a就一直向后推,直到遇见b或’?’为止,遇到其他字符则匹配错误)就好理解了。
要注意的是,*可以多次出现,如果s扫完了p后面还有’*’则也是true,如果出现了其他字符则错误。

源码:(language:python)

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

成绩:
116ms,85.49%,124ms,7.50%
cmershen的碎碎念:
本算法也不是很难理解,但是对于*的处理确实很巧妙。这道题似乎还有一种基于DP的解法。

你可能感兴趣的:(Hard-题目51:44. Wildcard Matching)