MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / dp_match

Function dp_match

dynamic_programming/regex_match.py:52–93  ·  view source on GitHub ↗

r""" Dynamic programming matching algorithm. | Time complexity: O(\|text\| * \|pattern\|) | Space complexity: O(\|text\| * \|pattern\|) :param text: Text to match. :param pattern: Pattern to match. :return: ``True`` if `text` matches `pattern`, ``False`` otherwise. >>>

(text: str, pattern: str)

Source from the content-addressed store, hash-verified

50
51
52def dp_match(text: str, pattern: str) -> bool:
53 r"""
54 Dynamic programming matching algorithm.
55
56 | Time complexity: O(\|text\| * \|pattern\|)
57 | Space complexity: O(\|text\| * \|pattern\|)
58
59 :param text: Text to match.
60 :param pattern: Pattern to match.
61 :return: ``True`` if `text` matches `pattern`, ``False`` otherwise.
62
63 >>> dp_match('abc', 'a.c')
64 True
65 >>> dp_match('abc', 'af*.c')
66 True
67 >>> dp_match('abc', 'a.c*')
68 True
69 >>> dp_match('abc', 'a.c*d')
70 False
71 >>> dp_match('aa', '.*')
72 True
73 """
74 m = len(text)
75 n = len(pattern)
76 dp = [[False for _ in range(n + 1)] for _ in range(m + 1)]
77 dp[0][0] = True
78
79 for j in range(1, n + 1):
80 dp[0][j] = pattern[j - 1] == "*" and dp[0][j - 2]
81
82 for i in range(1, m + 1):
83 for j in range(1, n + 1):
84 if pattern[j - 1] in {".", text[i - 1]}:
85 dp[i][j] = dp[i - 1][j - 1]
86 elif pattern[j - 1] == "*":
87 dp[i][j] = dp[i][j - 2]
88 if pattern[j - 2] in {".", text[i - 1]}:
89 dp[i][j] |= dp[i - 1][j]
90 else:
91 dp[i][j] = False
92
93 return dp[m][n]
94
95
96if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected