leetcode-44. Wildcard Matching

来源:互联网 发布:高等教育国家数据平台 编辑:程序博客网 时间:2024/06/03 19:59

leetcode-44. Wildcard Matching

题目:

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

这种题首先应该确定是用DP方法做。但是这题比10题简单一些。因为这里*可以匹配任意长度。所以对于*只要判断同一行的上列位置或者同一列的上一行位置是否为真就好。而?只要判断坐上方是否是真就好。具体解释讨论里很多。大体上思路差不多。当然这题似乎还有其他方法。但是如果对空间复杂度没有特殊要求的话还是DP的方法比较好理解
之前写过的第10题的博客

public class Solution {    public boolean isMatch(String s, String p) {        boolean [][] dp = new boolean[s.length()+1][p.length()+1];        dp[0][0] = true;        for(int i = 1 ; i < p.length()+1;i++)            dp[0][i]= p.charAt(i-1)=='*' ? dp[0][i-1]:false;        for(int i = 0 ; i < s.length(); i++)            for(int j = 0; j < p.length() ; j++){                if(s.charAt(i)==p.charAt(j) || p.charAt(j)=='?'){                    dp[i+1][j+1] = dp[i][j];                }                if(p.charAt(j)=='*'){                    dp[i+1][j+1] = dp[i+1][j]||dp[i][j+1];                }            }        return dp[s.length()][p.length()];    }}
0 0
原创粉丝点击