首页 > 其他 > 详细

LeetCode Wildcard Matching

时间:2015-03-06 11:20:36      阅读:296      评论:0      收藏:0      [点我收藏+]

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
题意:匹配两个字符串,?代表一个字符,*代表一个任意序列。

思路:贪心去做,重点是如果匹配"*",我们需要记录他的位置为start,和此时s串的位置tmp,然后对于p的下一位,我们是希望它能够匹配的,但是如果无法匹配的话,那么此时就需要用到我们标记的"*"的位置了,让"*"去多匹配一个字符,直到“*”的下一位能都匹配成功。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        const char *start = NULL, *tmp = NULL;
        while (*s != '\0') {
            if (*s == *p || *p == '?') {
                s++, p++;
                continue;
            }
            if (*p == '*') {
                start = p;
                p++;
                tmp = s;
                continue;
            }
            if (start != NULL) {
                p = start + 1;
                s = tmp + 1;
                tmp++;
                continue;
            }
            return false;
        }      
        while (*p == '*') p++;
        return *p == '\0';
    }
};



LeetCode Wildcard Matching

原文:http://blog.csdn.net/u011345136/article/details/44096509

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!