leetcode_c++:Wildcard Matching(044)

‘?’ 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
Subscribe to see which companies asked this question


题目的大意是,给出两串字符串s和p,规定符号?能匹配任意单个字符,*能匹配任意字符序列(包括空字符序列)。如果两串字符串完全匹配则返回true。

该题的难点主要在于出现时的匹配操作。和网上大多数做法相似,一开始使用递归完成,结果总是超时。后来使用几个变量用于记录遇到p中的时的下标,每次遇到一个*,就保留住当前字符串s和p的下标,然后s从当前下标往后扫描,如果不匹配,则s的下标加一,重复扫描。


#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    bool isMatch(string s, string p) {
        int s_size = s.size();
        int p_size = p.size();
        int s_index = 0, p_index = 0;
        int temp_s_index = -1, temp_p_index = -1;
        while (s_index < s_size)
        {
            if (p[p_index] == '?' || p[p_index] == s[s_index])
            {
                ++p_index;
                ++s_index;
                continue;
            }
            if (p[p_index] == '*') 
            {
                temp_p_index = p_index;
                temp_s_index = s_index;
                ++p_index;
                continue;
            }
            if (temp_p_index >= 0)
            {
                // 字符串p可能有多个*,因此只要出现过*,则需要更新当前匹配的下标
                p_index = temp_p_index + 1;
                s_index = temp_s_index + 1;
                // 当前坐标s与p不匹配,则s的坐标在原基础上加一,继续循环
                ++temp_s_index; 
                continue;
            }
            return false;
        }
        while (p[p_index] == '*') ++p_index;
        return p_index == p_size;
    }
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值