|
| 1 | +using System; |
| 2 | + |
| 3 | +namespace Algorithms.Strings.PatternMatching; |
| 4 | + |
| 5 | +public static class WildCardMatcher |
| 6 | +{ |
| 7 | + public static bool MatchPattern(string inputString, string pattern) |
| 8 | + { |
| 9 | + if (pattern.Length > 0 & pattern[0] == '*') |
| 10 | + { |
| 11 | + throw new ArgumentException("Pattern cannot start with *"); |
| 12 | + } |
| 13 | + |
| 14 | + var inputLength = inputString.Length + 1; |
| 15 | + var patternLength = pattern.Length + 1; |
| 16 | + |
| 17 | + // DP 2d matrix, where dp[i, j] is true if the first i characters in the input string match the first j characters in the pattern |
| 18 | + // This DP is initialized to all falses, as it is the default value for a boolean. |
| 19 | + var dp = new bool[inputLength, patternLength]; |
| 20 | + |
| 21 | + // Empty string and empty pattern are a match |
| 22 | + dp[0, 0] = true; |
| 23 | + |
| 24 | + // Since the empty string can only match a pattern that has a * in it, we need to initialize the first row of the DP matrix |
| 25 | + for (var j = 1; j < patternLength; j++) |
| 26 | + { |
| 27 | + if (pattern[j - 1] == '*') |
| 28 | + { |
| 29 | + dp[0, j] = dp[0, j - 2]; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Now using bottom-up approach to find for all remaining lenghts of input and pattern |
| 34 | + for (var i = 1; i < inputLength; i++) |
| 35 | + { |
| 36 | + for (var j = 1; j < patternLength; j++) |
| 37 | + { |
| 38 | + // If the characters match or the pattern has a ., then the result is the same as the previous characters |
| 39 | + if (inputString[i - 1] == pattern[j - 1] || pattern[j - 1] == '.') |
| 40 | + { |
| 41 | + dp[i, j] = dp[i - 1, j - 1]; |
| 42 | + } |
| 43 | + else if (pattern[j - 1] == '*') |
| 44 | + { |
| 45 | + if (dp[i, j - 2]) |
| 46 | + { |
| 47 | + dp[i, j] = true; |
| 48 | + } |
| 49 | + else if (inputString[i - 1] == pattern[j - 2] || pattern[j - 2] == '.') |
| 50 | + { |
| 51 | + dp[i, j] = dp[i - 1, j]; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return dp[inputLength - 1, patternLength - 1]; |
| 58 | + } |
| 59 | +} |
0 commit comments