Leetcode_wildcard-matching(c++ and python version)

62 篇文章 0 订阅
52 篇文章 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
思路:(1)如果*s与*p相等或者*p=='?', s++, p++, 继续下一次判断;
            (2)若*p=='*', 先用copyp和copys分别把p和s存一份(其实存的是起始位置, 可以做*匹配的起始位置), s的位置不变,++p (这里其实是*不匹配任何,若之后不匹配,再退回来匹配)
            (3)若copyp不为空,即之前存在*,现在可以匹配,p = copyp + 1, 即从*之后开始, s = ++copys, s也是从当初copys开始,不过copys本身也要自增(记录*已匹配字符数),每自增一次,代表p中的*匹配多一个字符,每次如此p = copyp + 1, 从*后开始匹配,不匹配的话再重复(即*再多匹配s中的一个字符), 直到s为空.
           (4)前三都不符合,无法匹配。
可参考:http://blog.csdn.net/doc_sgl/article/details/12721187

c++参考代码:
class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        const char *copyp = NULL, *copys = s;
        while(*s)
        {
            if(*s==*p || *p=='?')
            {
                ++s;
                ++p;
            }
            else if(*p=='*')
            {
                copyp = p++;
                copys = s;
            }
            else if(copyp)
            {
                p = copyp+1;
                s = ++copys;
            }
            else
                return false;
        }
        while(*p && *p=='*')
            ++p;
        return !(*p);
    }
};


python 参考代码:
class Solution:
    # @param s, an input string
    # @param p, a pattern string
    # @return a boolean
    def isMatch(self, s, p):
        p += '\0'
        copys = copyp = ""
        flag = True
        while s:
            if s[0] == p[0] or p[0] == '?':
                s = s[1:]
                p = p[1:]
            elif p[0] == '*':
                copyp = p
                copys = s
                p = p[1:]
            elif copyp:
                copys = copys[1:]
                s = copys
                p = copyp[1:]
            else:
                return False

        while p and p[0]=='*':
            p = p[1:]
        return p[0]=='\0'


python的代码真是折腾死了,没有指针真是不方便啊!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值