Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

通配符匹配 #53

Open
louzhedong opened this issue Sep 7, 2018 · 0 comments
Open

通配符匹配 #53

louzhedong opened this issue Sep 7, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第44题

给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?''*' 的通配符匹配。

'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串(包括空字符串)。

两个字符串完全匹配才算匹配成功。

说明:

  • s 可能为空,且只包含从 a-z 的小写字母。
  • p 可能为空,且只包含从 a-z 的小写字母,以及字符 ?*

示例 1:

输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。

示例 2:

输入:
s = "aa"
p = "*"
输出: true
解释: '*' 可以匹配任意字符串。

示例 3:

输入:
s = "cb"
p = "?a"
输出: false
解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。

示例 4:

输入:
s = "adceb"
p = "*a*b"
输出: true
解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce".

示例 5:

输入:
s = "acdcb"
p = "a*c?b"
输入: false

思路

采用动态规划进行解答

要考虑字符串为空的情况,dp[0][0]中存放当两个字符串都为空时的结果

解答

/**
 * @param {string} s
 * @param {string} p
 * @return {boolean}
 */
var isMatch = function (s, p) {
  var sLength = s.length;
  var pLength = p.length;
  var dp = [];
  for (var i = 0; i <= sLength; i++) {
    dp[i] = [];
    for (var j = 0; j <= pLength; j++) {
      dp[i][j] = false;
    }
  }
  dp[0][0] = true;

  for (var j = 1; j <= pLength; j++) {
    if (p[j - 1] == '*' && dp[0][j - 1]) {
      dp[0][j] = true;
    }
  }

  for (var i = 1; i <= sLength; i++) {
    for (var j = 1; j <= pLength; j++) {
      if ((s[i - 1] == p[j - 1]) || (p[j - 1] == '?')) {
        if (dp[i - 1][j - 1]) {
          dp[i][j] = true;
        }
      } else if (p[j - 1] == '*') {
        dp[i][j] = dp[i - 1][j - 1] || dp[i][j - 1] || dp[i - 1][j];
      }
    }
  }
  console.log(dp);
  return dp[sLength][pLength];
};

console.log(isMatch("a", ""));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant