【leetcode】 Wildcard Matching

本文介绍了一种实现通配符模式匹配的算法,支持 '?' 和 '*' 两种通配符,并提供了详细的 C++ 实现代码。该算法能完整匹配输入字符串而非部分匹配。

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

from : https://leetcode.com/problems/wildcard-matching/

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
public class Solution {
    public boolean isMatch(String s, String p) {
	    int i=0, j=0;
	    int ls = s.length(), lp = p.length();
	    int statIdx = -1, sIdx = -1;
	    
	    while(i < ls) {
	        if(j<lp && (s.charAt(i) == p.charAt(j) || '?' == p.charAt(j))) { //match
	            ++i;
	            ++j;
	            continue;
	        }
	        if(j<lp && '*' == p.charAt(j)) { 
	        	statIdx = j; // record star
	            ++j; //match from next p
	            sIdx = i; // record the position of s , star match 0
	            continue;
	        } 
	        if(0 <= statIdx) { //if have star in front then backtrace
	            j = statIdx + 1; //reset the position of p 
	            i = sIdx + 1; 
	            ++sIdx; //star match 1,2,3,4,5....
	            continue;
	        }
	        return false; //if not match return false
	    }
	    while(j < lp && '*' == p.charAt(j)) ++j; //skip continue star
	    return j == lp; // successful match
    }
}

class Solution {
public:
    bool isMatch(string s, string p) {
        int i=0, j=0, ls = s.size(), lp = p.size(), is = -1, jp = -1;
        while(i < ls) {
            if(j < lp && (s[i] == p[j] || '?' == p[j])) {
                ++i;
                ++j;
                continue;
            }
            if(j < lp && '*' == p[j]) {
                is = i;
                jp = j;
                ++j;
                continue;
            }
            if(0 <= is) {
                ++is;
                i = is;
                j = jp + 1;
                continue;
            }
            return false;
        }
        while(j < lp && '*' == p[j]) ++j;
        return j == lp;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值