Leetcode 44: Wildcard Matching

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

 Solution 1: backtracking, works for regular cases but it times out for some long input.

 1 public class Solution {
 2     public bool IsMatch(string s, string p) {
 3         return DFS(s, p, 0, 0);
 4     }
 5     
 6     private bool DFS(string s, string p, int sStart, int pStart)
 7     {
 8         if (sStart >= s.Length)
 9         {
10             while (pStart < p.Length)
11             {
12                 if (p[pStart] != *) break;
13                 pStart++;
14             }
15             
16             return pStart >= p.Length;
17         }
18         
19         if (pStart >= p.Length) return false;
20         
21         if (p[pStart] == ? || p[pStart] == s[sStart])
22         {
23             return DFS(s, p, sStart + 1, pStart + 1);
24         }
25         else if (p[pStart] == *)
26         {
27             while (pStart < p. Length && p[pStart] == *)
28             {
29                 pStart++;
30             }
31             
32             for (int i = sStart; i <= s.Length; i++)
33             {
34                 if (DFS(s, p, i, pStart))
35                 {
36                     return true;
37                 }
38             }
39         }
40         
41         return false;
42     }
43 }

 

 There are both a linear sort of backtracking solution and a dp solution, please see leetcode.

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

Leetcode 44: Wildcard Matching

LeetCode-44-Wildcard Matching

LeetCode44 Wildcard Matching

leetcode-44. Wildcard Matching

[动态规划] leetcode 44 Wildcard Matching

LeetCode 44 Wildcard Matching(字符串匹配问题)