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

Leetcode 44: Wildcard Matching

时间:2017-11-08 14:57:38      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:tracking   tar   sort   sequence   star   work   type   question   i++   

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

标签:tracking   tar   sort   sequence   star   work   type   question   i++   

原文地址:http://www.cnblogs.com/liangmou/p/7803462.html

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