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

44. Wildcard Matching

时间:2019-10-17 01:31:57      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:new   ring   substring   which   一个   div   nbsp   pac   should   

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: ‘*‘ matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: ‘?‘ matches ‘c‘, but the second letter is ‘a‘, which does not match ‘b‘.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first ‘*‘ matches the empty sequence, while the second ‘*‘ matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false
class Solution {
    public boolean isMatch(String s, String p) {
        char[] sc = s.toCharArray();
        char[] pc = p.toCharArray();
        int m = sc.length, n = pc.length;
        boolean[][] dp = new boolean[m+1][n+1];
        dp[0][0] = true;
        
        for(int i = 1; i < n + 1; i++){
            if(pc[i-1] == ‘*‘) dp[0][i] = dp[0][i - 1];
        }
        for(int i = 1; i < m + 1; i++){
            for(int j = 1; j < n + 1; j++){
                if(sc[i - 1] == pc[j - 1] || pc[j - 1] == ‘?‘){
                    dp[i][j] = dp[i - 1][j - 1];
                }
                else if(pc[j - 1] == ‘*‘){
                    dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
                }
            }
        }
        return dp[m][n];
    }
}

技术图片

 

第一行表示pattern和空字符匹配,除第一个外都为false。

第一列表示string和空pattern匹配,除pattern也为空为true外都为false。

技术图片

 

 

 https://www.cnblogs.com/Xieyang-blog/p/9006832.html

44. Wildcard Matching

标签:new   ring   substring   which   一个   div   nbsp   pac   should   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11689635.html

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