Algorithm:通配符匹配

本文探讨了一种高效的算法实现,用于支持'?'和'*'通配符的字符串匹配,通过回溯和状态跟踪优化了处理'?'和'*'的复杂情况,提高了匹配效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

请实现支持'?'and'*'.的通配符模式匹配

'?' 可以匹配任何单个字符。
'*' 可以匹配任何字符序列(包括空序列)。

返回两个字符串是否匹配

函数声明为:

bool isMatch(const char *s, const char *p)

下面给出一些样例:

isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "d*a*b") → false

示例1

输入

"ab","?*"

返回值

true

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if(*s == '\0')
        {
            if(*p == '\0')
            {
                return true;
            }
            else
            {
                if(*p == '*')
                {
                    return isMatch(s, p+1);
                }
                else
                {
                    return false;
                }
            }
        }
        else
        {
            if(*p == *s || *p == '?')
            {
                if(strlen(p) == 1 && strlen(s) == 1)
                    return true;
                else
                    return isMatch(s+1, p+1);
            }
            else if(*p == '*')
            {
                if(strlen(p) == 1)
                {
                    return true;
                }
                else if(isMatch(s, p+1))
                {
                    return true;
                }
                else
                {
                    return isMatch(s+1, p);
                }
            }
            else
            {
                return false;
            }
        }
    }
};

解题中。。。 

上面这个解题方法,应该没问题。只是时间太长。下面是效率高的解题方法,不需要递归运算。

解题思路:使用回溯的方法。记录节点。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        int s_index = 0;
        int p_index = 0;

        int s_recall = 0;
        int p_recall = 0;

        while(s[s_index] != '\0')
        {
           if(s[s_index] == p[p_index] || p[p_index] == '?')
           {
               s_index++;
               p_index++;
           }
           else if(p[p_index] == '*')
           {
              p_index++;
              s_recall = s_index+1;
              p_recall = p_index;
           }
           else if(p_recall)
           {
               s_index = s_recall;
               p_index = p_recall;
               s_recall = s_index+1;
           }
           else
           {
              return false;
           }
        }

        while(p[p_index] == '*')
        {
            p_index++;
        }

        return (p[p_index] == '\0' ? true : false);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AllenSun-1990

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值