leetcode--Wildcard Matching

本文介绍了一种通配符匹配算法,支持 '?' 和 '*' 的模式匹配。通过两种不同的实现方式来解决完全匹配的问题,适用于动态规划、回溯、贪心等技术领域。

摘要生成于 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


题意:

分类:动态规划,回溯,贪心,字符串


解法1:

public class Solution {
    public boolean isMatch(String s, String p) {
        int slen = s.length()+1;
        int plen = p.length()+1;
        boolean[][] dp = new boolean[slen][plen];
        dp[0][0]=true;
        
        for(int i=1; i<plen; i++){
            if(p.charAt(i-1)=='*')
                dp[0][i] = true;
            else
                break;
        }
        
        for(int i=1; i<slen; i++){
            for(int j=1; j<plen; j++){
                if(p.charAt(j-1)=='*' && (dp[i-1][j] || dp[i][j-1] || dp[i-1][j-1]))
                    dp[i][j] = true;
                else if(dp[i-1][j-1] && (p.charAt(j-1)=='?' || p.charAt(j-1)==s.charAt(i-1))){
                    dp[i][j] = true;
                }
            }
        }
        return dp[slen-1][plen-1];
    }
}


解法2:

if(p.length()==0)  
        return s.length()==0;  
    boolean[] res = new boolean[s.length()+1];  
    res[0] = true;  
    for(int j=0;j<p.length();j++)  
    {  
        if(p.charAt(j)!='*')  
        {  
            for(int i=s.length()-1;i>=0;i--)  
            {  
                res[i+1] = res[i]&&(p.charAt(j)=='?'||s.charAt(i)==p.charAt(j));  
            }  
        }  
        else  
        {  
            int i = 0;  
            while(i<=s.length() && !res[i])  
                i++;  
            for(;i<=s.length();i++)  
            {  
                res[i] = true;  
            }  
        }  
        res[0] = res[0]&&p.charAt(j)=='*';  
    }  
    return res[s.length()];  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值