44. 通配符匹配 Wildcard Matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

  • '?' Matches any single character.
  • '*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

 

方法:

动态规划

dp[0][0]=True,即当字符串s和模式p均为空时,匹配成功;
dp[i][0]=False,即空模式无法匹配非空字符串;
dp[0][j] 需要分情况讨论:因为星号才能匹配空字符串,所以只有当模式p的前j个字符都为*时,dp[0][j]才为真。
public boolean isMatch(String s, String p) {
        int m = s.length();
        int n = p.length();
        boolean [][] dp = new boolean[m + 1][n + 1];
        dp[0][0] = true;
        for (int i = 1; i <= n; ++i){
            if(p.charAt(i - 1) == '*'){
                dp[0][i] = true;
            }else {
                break;
            }
        }
        for(int i = 1; i <= m; ++i){
            for(int j = 1; j <= n; ++j){
                if (p.charAt(j -1) == '*'){
                    dp[i][j] = dp[i][j - 1] ||dp[i - 1][j];
                }else if(p.charAt(j - 1) == '?' || s.charAt(i -1) == p.charAt(j -1)){
                    dp[i][j]=dp[i - 1][j - 1];
                }
            }
        }
        return dp[m][n];

    }

 

参考链接:

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

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

posted @ 2020-12-23 10:16  diameter  阅读(116)  评论(0编辑  收藏  举报