leetcode--Wildcard Matching

本文介绍了一种通配符匹配算法,支持 '?' 和 '*' 的模式匹配。通过动态规划方法实现,能够完整匹配输入字符串,提供了两种不同的 Java 实现方案。

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

[java]  view plain  copy
  1. public class Solution {  
  2.     public boolean isMatch(String s, String p) {  
  3.         int slen = s.length()+1;  
  4.         int plen = p.length()+1;  
  5.         boolean[][] dp = new boolean[slen][plen];  
  6.         dp[0][0]=true;  
  7.           
  8.         for(int i=1; i<plen; i++){  
  9.             if(p.charAt(i-1)=='*')  
  10.                 dp[0][i] = true;  
  11.             else  
  12.                 break;  
  13.         }  
  14.           
  15.         for(int i=1; i<slen; i++){  
  16.             for(int j=1; j<plen; j++){  
  17.                 if(p.charAt(j-1)=='*' && (dp[i-1][j] || dp[i][j-1] || dp[i-1][j-1]))  
  18.                     dp[i][j] = true;  
  19.                 else if(dp[i-1][j-1] && (p.charAt(j-1)=='?' || p.charAt(j-1)==s.charAt(i-1))){  
  20.                     dp[i][j] = true;  
  21.                 }  
  22.             }  
  23.         }  
  24.         return dp[slen-1][plen-1];  
  25.     }  
  26. }  


解法2:

[java]  view plain  copy
  1. if(p.length()==0)    
  2.         return s.length()==0;    
  3.     boolean[] res = new boolean[s.length()+1];    
  4.     res[0] = true;    
  5.     for(int j=0;j<p.length();j++)    
  6.     {    
  7.         if(p.charAt(j)!='*')    
  8.         {    
  9.             for(int i=s.length()-1;i>=0;i--)    
  10.             {    
  11.                 res[i+1] = res[i]&&(p.charAt(j)=='?'||s.charAt(i)==p.charAt(j));    
  12.             }    
  13.         }    
  14.         else    
  15.         {    
  16.             int i = 0;    
  17.             while(i<=s.length() && !res[i])    
  18.                 i++;    
  19.             for(;i<=s.length();i++)    
  20.             {    
  21.                 res[i] = true;    
  22.             }    
  23.         }    
  24.         res[0] = res[0]&&p.charAt(j)=='*';    
  25.     }    
  26.     return res[s.length()];  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47359779

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值