19.2.4 [LeetCode 44] Wildcard Matching

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.2.4 [LeetCode 44] Wildcard Matching相关的知识,希望对你有一定的参考价值。

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

题意

通配符匹配,?代表单个特定字符,*代表若干长度的字符串

题解

一看就很像这题,所以想都没想用了dp,但是比较慢

 1 class Solution {
 2 public:
 3     bool isMatch(string s, string p) {
 4         s = " " + s, p = " " + p;
 5         int l1 = s.length(), l2 = p.length();
 6         vector<vector<bool>>dp(l1);
 7         for (int i = 0; i < l1; i++)dp[i].resize(l2);
 8         for (int i = 0; i < l1; i++)
 9             for (int j = 0; j < l2; j++)
10                 dp[i][j] = false;
11         dp[0][0] = true;
12         for (int i = 1; i < l2; i++) {
13             if (p[i] == \'*\') {
14                 int j = 0;
15                 for (; j < l1; j++)
16                     if (dp[j][i - 1])break;
17                 if (j < l1)
18                     while (j < l1) {
19                         dp[j][i] = true;
20                         j++;
21                     }
22             }
23             else if (p[i] == \'?\') {
24                 for (int j = 0; j < l1 - 1; j++)
25                     if (dp[j][i - 1])
26                         dp[j + 1][i] = true;
27             }
28             else {
29                 for (int j = 1; j < l1; j++)
30                     if (s[j] == p[i] && dp[j - 1][i - 1])
31                         dp[j][i] = true;
32             }
33         }
34         return dp[l1 - 1][l2 - 1];
35     }
36 };
View Code

我看见有解法是贪心,貌似比我这个快得多,但是我今天不想再看了,以后再说

以上是关于19.2.4 [LeetCode 44] Wildcard Matching的主要内容,如果未能解决你的问题,请参考以下文章

19.2.4 [LeetCode 43] Multiply Strings

replicate-wild-do-table与replicate-wild-ignore-table

网球比赛中的wild card是啥意思?

javascript Wild Magic.js

poj 1816 Wild Words

html Wild Nutrition Secondary Blog菜单