字符串通配符匹配问题

问题: S代表原字符串,P代表模式串,包含* (匹配0或者多个)和?(匹配一个)

思路:动态规划

  • dp[i][j] 代表 S的前i个字符和P的前j个字符是否匹配, 最后返回dp[s.length()][p.length()]
  • p[j-1]==* 则 dp[i][j] = dp[i-1][j] || dp[i-1][j-1] || dp[i][j-1]   分别代表 * 匹配0个,一个,多个字符
  • p[j-1]!=*  如果s[i-1] == p[j-1]或者p[j-1]==?  当前字符匹配,则 dp[i][j]=dp[i-1][j-1] ,否则默认为false
  • dp[0][0] = true; 
  • dp[0][j] 需要处理 模式串以 ”**。。。“开头的情况, 即任意全部字符为 * 的模式串可以匹配 0 个长度的字符 
  • dp[i][0] 模式串开头为 * 时,dp[i][0]代表任意长度字符串可以与 * 匹配
class Solution {
    public boolean isMatch(String s, String p) {
        if(null==s || null==p) return false;
        if("*".equals(p) || s.equals(p)) return true;

        int sl = s.length(), pl=p.length();
        if(pl==0) return false;  //模式串为空,匹配串不为空
        boolean[][] dp = new boolean[sl+1][pl+1];
        
        char[] sc = s.toCharArray();
        char[] pc = p.toCharArray();

        dp[0][0] =true;
        
        if(pc[0]=='*') {
            int j=0;
            while(j<pl && pc[j++]=='*') dp[0][j]=true;  //处理模式串“***。。”的情况

            for(int i=1;i<=sl;i++) dp[i][0]=true;  
        }

        for(int i =1;i<=sl;i++){
            for(int j=1;j<=pl;j++){
                if(pc[j-1]=='*')    dp[i][j] = dp[i-1][j] || dp[i][j-1] || dp[i-1][j-1];
                else if(pc[j-1]==sc[i-1] || pc[j-1]=='?')    dp[i][j] = dp[i-1][j-1];
            }
        }
        return dp[sl][pl];
    }
}  

  

  

猜你喜欢

转载自www.cnblogs.com/zzm96/p/12896545.html