码迷,mamicode.com
首页 > 其他好文 > 详细

44. 通配符匹配 Wildcard Matching

时间:2020-12-29 11:12:41      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:模式   pre   ret   single   character   problems   seq   链接   card   

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/

44. 通配符匹配 Wildcard Matching

标签:模式   pre   ret   single   character   problems   seq   链接   card   

原文地址:https://www.cnblogs.com/diameter/p/14177012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!