首页 » 编程之美 » 正文

[leetcode_44]Wildcard Matching

dfs一直超时,就算用了备忘录也超时。代码附上,纪念一下:

class Solution {
public:
    bool isMatch(const char <em>s, const char *p) {
        // Note: The Solution object is instantiated only once and is reused by each test case.<br />
        const char</em> tmp = p;<br />
        int cnt = 0;<br />
        while (<em>tmp != '&#92;&#48;') if (</em>(tmp++) != '*') cnt++;<br />
        if (cnt &gt; strlen(s)) return false;</p>

<pre><code>    if(strlen(s) == 0) {
        for(int i = 0;i &amp;lt; strlen(p);i++) {
            if(p[i] != '*')return false;
        }
        return true;
    }

    int **dp;
    dp = new int*[strlen(s) + 1];
    for(int i = 0;i &amp;lt;= strlen(s);i++) {
        dp[i] = new int[strlen(p) + 1];
    }
    dp[0][0] = 1;
    int i = 0;
    while(p[i++] == '*') dp[0][i] = 1;
    for(int i = 1;i &amp;lt;= strlen(s);i++) {
        for(int j = 1;j &amp;lt;= strlen(p);j++) {
            if(dp[i-1][j-1] == 1&amp;amp;&amp;amp;(s[i-1] == p[j-1] || p[j-1] == '?')) {
                dp[i][j] = 1;
            }
            if(p[j-1] == '*' &amp;amp;&amp;amp; (dp[i][j-1] == 1 || dp[i-1][j-1] == 1 || dp[i-1][j] == 1)) {
                dp[i][j] = 1;
            }
        }
    }
    if(dp[strlen(s)][strlen(p)] == 1)return true;
    else
        return false;
}
</code></pre>

<p>};

发表评论