LeetCode -- Wildcard Matching

本文介绍了一种通配符匹配算法的实现,该算法支持 '?' 和 '*' 两种通配符,其中 '?' 可匹配任意单个字符,'*' 可匹配任意字符序列。通过动态规划方法,文章详细阐述了如何判断一个字符串 s 是否能与另一个带有通配符的字符串 p 完全匹配。

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

题目描述:


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


实现字符串匹配。输入字符串s,和字符串匹配p,?可被替换为任何非空字符,*可替换空字符或任何字符。
设,arr[i,j]表示s的第i个字符是否和p的第j个字符匹配。对于s[i]和p[j],分为三种情况:
arr[i,j] = arr[i-1,j-1] ,p[j]=?
arr[i,j] = arr[i-1,j-1] && s[i-1] == p[j-1] ,p[j]为普通字符
arr[i,j] = arr[i-1,j-1]||arr[i-1,j]||arr[i,j-1] ,p[j]为*


实现代码:


public class Solution {
    public bool IsMatch(string s, string p) {
        var dp = new bool[s.Length + 1, p.Length + 1]; 
    	dp[0,0]  = true; // s is empty , pattern is empty, match
    	
    	// s is not empty , patter is empty , not match
    	for (var i = 0;i < s.Length; i++){
    		dp[i+1,0] = false;
    	}
    	
    	// pattern not empty, s is empty , not match
        for (var i = 0;i < p.Length; i++){
    		dp[0, i+1] = p[i] == '*' && dp[0, i];
    	}
    	
    	for (var i = 1; i <= s.Length; i++){
    		for (var j = 1;j <= p.Length; j++){
    			if (p[j-1] == '?'){
    				dp[i,j] = dp[i-1,j-1]; // depends on previous match or no
    			}
    			else if(p[j-1] == '*'){
    				// 1. ab a*
    				// 2. bavfdc b*
    				// pattern j matches string i - 1 (* is any char)
    				// or
    				// pattern j-1 matches string i (* can be removed)
    				//Console.WriteLine(i+","+j);
    				dp[i,j] = dp[i-1,j] || dp[i, j-1] || dp[i-1,j-1];
    			}
    			else{
    				// pattern is a normal charactor , previous match also current char should match
    				dp[i,j] = dp[i-1,j-1] && s[i-1] == p[j-1];
    			}
    		}
    	}
    	//Console.WriteLine(dp);
    	return dp[s.Length,p.Length];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值