LeetCode 44. Wildcard Matching

来源:互联网 发布:linux ping的超时时间 编辑:程序博客网 时间:2024/04/27 20:44

题目描述

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

题目解析

这里我使用了leetcode10. Regular Expression Matching(hard)的解题思路,逻辑如下:
c[i][j] 代表s[:,i]与p[:,j]是否匹配。
p[j]==’*’ then
1.c[i][j]=c[i][j-1]; ‘*’被匹配0次;
2. c[i][j]=c[i-1][j];’*’被匹配1次及以上;
p[j]==’?’then
c[i][j]==c[i-1][j-1];
else
c[i][j]==c[i-1][j-1]&&s[i]==p[j];
但是这里出现了一点问题,运行时间1692ms,排在后5%,一定是有另外的更快的解法。

第一次尝试的代码

class Solution {public:    bool isMatch(string s, string p) {        int m=s.size(),n=p.size();        vector<vector<bool> >c(m+1,(vector<bool>(n+1,false)));        c[0][0]=true;        for(int i=0;i<=m;i++)        {            for(int j=1;j<=n;j++)            {                if(p[j-1]=='*')                {                    c[i][j]=c[i][j-1]||i>0&&c[i-1][j];                }                else if(p[j-1]=='?')                {                    c[i][j]=i>0&&c[i-1][j-1];                }                else                {                    c[i][j]=i>0&&s[i-1]==p[j-1]&&c[i-1][j-1];                }            }        }        return c[m][n];    }};
0 0
原创粉丝点击