LeetCode Online Judge 题目C# 练习 - 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
public static bool WildcardMatching(string s, string p) { return WildcardMathchingHepler(s, 0, p, 0); } public static bool WildcardMathchingHepler(string s, int i, string p, int j) { if (i == s.Length) { if (j == p.Length) return true; else if (p[j] == '*') return WildcardMathchingHepler(s, i, p, j + 1); else return false; } else { if (j == p.Length) return false; else if (p[j] == '?' || (s[i] == p[j])) return WildcardMathchingHepler(s, i + 1, p, j + 1); else if (p[j] == '*') return WildcardMathchingHepler(s, i, p, j + 1) || WildcardMathchingHepler(s, i + 1, p, j); else return false; } }
代码分析:
递归。
1 public static bool WildcardMatchingDP(string s, string p) 2 { 3 if (p.Length == 0 && s.Length == 0) 4 return true; 5 else if (p.Length == 0 && p[0] != '*') 6 return false; 7 else if (s.Length == 0) 8 return false; 9 10 int countp = 0; 11 for (int i = 0; i < p.Length; i++) 12 { 13 if (p[i] != '*') 14 countp++; 15 } 16 17 if (countp > s.Length) 18 return false; 19 20 bool[,] matrix = new bool[p.Length, s.Length]; 21 countp = 0; 22 for (int i = 0; i < p.Length; i++) 23 { 24 if (p[i] != '*') 25 countp++; 26 for (int j = 0; j < s.Length; j++) 27 { 28 if (i == 0 && j == 0) 29 { 30 if (p[i] == '?' || p[i] == '*' || p[i] == s[j]) 31 matrix[i, j] = true; 32 else 33 return false; 34 } 35 else if (p[i] == '*') 36 { 37 if (i - 1 < 0) 38 matrix[i, j] = true; 39 else if (j - 1 < 0) 40 { 41 if(matrix[i - 1, j] == true) 42 matrix[i, j] = true; 43 else 44 matrix[i, j] = false; 45 } 46 else if (matrix[i - 1, j] == true || matrix[i - 1, j - 1] == true || matrix[i, j - 1] == true) 47 matrix[i, j] = true; 48 else 49 matrix[i, j] = false; 50 } 51 else if ((p[i] == '?' || p[i] == s[j]) && j + 1 >= countp) 52 { 53 if (i - 1 < 0) 54 matrix[i, j] = false; 55 else if (j - 1 < 0) 56 { 57 if (p[i - 1] == '*' && matrix[i - 1, j] == true) 58 matrix[i, j] = true; 59 else 60 matrix[i, j] = false; 61 } 62 else if (matrix[i - 1, j - 1] == true && p[i - 1] != '*') 63 matrix[i, j] = true; 64 else if (p[i - 1] == '*' && matrix[i - 1, j] == true) 65 { 66 if (i - 2 < 0 || j - 1 < 0) 67 matrix[i, j] = true; 68 else 69 matrix[i, j] = matrix[i - 2, j - 1]; 70 } 71 else 72 matrix[i, j] = false; 73 } 74 else 75 { 76 matrix[i, j] = false; 77 } 78 } 79 } 80 81 return matrix[p.Length - 1, s.Length - 1]; 82 }
代码分析:
DP。