前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 44 Wildcard Matching 推荐

Leetcode 44 Wildcard Matching 推荐

作者头像
triplebee
发布2018-01-12 15:06:33
5750
发布2018-01-12 15:06:33
举报
文章被收录于专栏:计算机视觉与深度学习基础

Implement wildcard pattern matching with support for '?' and '*'.

代码语言:javascript
复制
'?' 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

字符串匹配,?代表一个字符,*代表任意字符串

比较容易想到的是深搜,我一开始也是这么做的,然后发现跑得比较慢,

看到有人用DP做,不过速度也不是太快,

再后来看到了贪心!

?和匹配的字符正常匹配,遇到*记录两个串当前的位置,并默认*为空串,继续往后

遇到无法匹配的情况,返回上一个*号的位置,增加*的匹配字符数。

为什么只返回上一个*,不用管前面的呢?

因为即使前面的*少表示了若干个字符,在两个*中间全部匹配的情况下,后面的*也可以表示前面少掉的若干字符!

虽然复杂度不是线性的,但是比起直接暴搜少了很多情况。

代码语言:javascript
复制
class Solution {
public:
    bool isMatch(string s, string p) {
        int ss=0,ps=0,spos=-1,ppos=-1;
        while(ss<s.size())
        {
            if(s[ss]==p[ps] || p[ps]=='?')
            {
                ss++;
                ps++;
            }
            else if(p[ps]=='*')
            {
                spos=ss;
                ppos=ps++;
            }
            else
            {
                if(ppos>-1)
                {
                    ss=++spos;
                    ps=ppos+1;
                }
                else
                 return false;
            }
        }
        while(p[ps]=='*') ps++;
        return ps==p.size();
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-09-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档