码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 044 Wildcard Matching

时间:2015-02-07 21:35:36      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

题目要求: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

参考网址:http://blog.csdn.net/pickless/article/details/9787227

代码如下:

class Solution {
public:
    bool initCheck(const char *s, const char *p) {
        int l1 = 0;
        int idx = 0, l2 = 0;
        
        while (s[l1] != \0) {
            l1++;
        }
        while (p[idx] != \0) {
            l2 += p[idx++] != * ? 1 : 0;
        }
        
        return l1 >= l2;
    }
    
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!initCheck(s, p)) {
            return false;
        } 
        
        int l = 0;
        while (p[l++] != \0);
          
        
        bool prev[l], f[l];
        memset(f, false, sizeof(bool) * l);
        memset(prev, false, sizeof(bool) * l);
        
        bool isFirst = true;
        for (int i = 0; i < l; i++) {
            if (p[i] == *) {
                f[i] = i == 0 || f[i - 1];
            }            
            else if ((p[i] == ? || p[i] == *s) && isFirst) {
                isFirst = false;
                f[i] = true;
            }
            else {
                break;
            }
        }
        s++;
        
        while (*(s - 1) != \0) {
            memcpy(prev, f, l);
            memset(f, false, sizeof(bool) * l);
            
            for (int i = 0; i < l; i++) {
                if (prev[i]) {
                    f[i] = f[i] || p[i] == *;
                    f[i + 1] = f[i + 1] || p[i + 1] == ? || p[i + 1] == *s;
                }
                else if (i == 0 || f[i - 1]) {
                    f[i] = f[i] || p[i] == *;
                }
            }
            s++;
        }    
        
        return f[l - 1];
    }
};

 

LeetCode 044 Wildcard Matching

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4279273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!