标签: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 }
Leetcode 44: Wildcard Matching
标签:tracking tar sort sequence star work type question i++
原文地址:http://www.cnblogs.com/liangmou/p/7803462.html