uses bottom-up dynamic programming solution for matching the input string with a given pattern. Runtime: O(len(input_string)*len(pattern)) Arguments -------- input_string: str, any string which should be compared with the pattern pattern: str, the string that represent
(input_string: str, pattern: str)
| 8 | |
| 9 | |
| 10 | def match_pattern(input_string: str, pattern: str) -> bool: |
| 11 | """ |
| 12 | uses bottom-up dynamic programming solution for matching the input |
| 13 | string with a given pattern. |
| 14 | |
| 15 | Runtime: O(len(input_string)*len(pattern)) |
| 16 | |
| 17 | Arguments |
| 18 | -------- |
| 19 | input_string: str, any string which should be compared with the pattern |
| 20 | pattern: str, the string that represents a pattern and may contain |
| 21 | '.' for single character matches and '*' for zero or more of preceding character |
| 22 | matches |
| 23 | |
| 24 | Note |
| 25 | ---- |
| 26 | the pattern cannot start with a '*', |
| 27 | because there should be at least one character before * |
| 28 | |
| 29 | Returns |
| 30 | ------- |
| 31 | A Boolean denoting whether the given string follows the pattern |
| 32 | |
| 33 | Examples |
| 34 | ------- |
| 35 | >>> match_pattern("aab", "c*a*b") |
| 36 | True |
| 37 | >>> match_pattern("dabc", "*abc") |
| 38 | False |
| 39 | >>> match_pattern("aaa", "aa") |
| 40 | False |
| 41 | >>> match_pattern("aaa", "a.a") |
| 42 | True |
| 43 | >>> match_pattern("aaab", "aa*") |
| 44 | False |
| 45 | >>> match_pattern("aaab", ".*") |
| 46 | True |
| 47 | >>> match_pattern("a", "bbbb") |
| 48 | False |
| 49 | >>> match_pattern("", "bbbb") |
| 50 | False |
| 51 | >>> match_pattern("a", "") |
| 52 | False |
| 53 | >>> match_pattern("", "") |
| 54 | True |
| 55 | """ |
| 56 | |
| 57 | len_string = len(input_string) + 1 |
| 58 | len_pattern = len(pattern) + 1 |
| 59 | |
| 60 | # dp is a 2d matrix where dp[i][j] denotes whether prefix string of |
| 61 | # length i of input_string matches with prefix string of length j of |
| 62 | # given pattern. |
| 63 | # "dp" stands for dynamic programming. |
| 64 | dp = [[0 for i in range(len_pattern)] for j in range(len_string)] |
| 65 | |
| 66 | # since string of zero length match pattern of zero length |
| 67 | dp[0][0] = 1 |
no outgoing calls
no test coverage detected