|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +#------------------------------------------------------------------------------ |
| 4 | +# First Solution |
| 5 | +# Not too efficient with all the recursion lol |
| 6 | +#------------------------------------------------------------------------------ |
| 7 | + |
| 8 | +class Solution(object): |
| 9 | + def isMatch(self, s, p): |
| 10 | + """ |
| 11 | + :type s: str |
| 12 | + :type p: str |
| 13 | + :rtype: bool |
| 14 | + """ |
| 15 | + i = 0 |
| 16 | + for j in range(len(p)): |
| 17 | + # If str is longer than pattern -> false |
| 18 | + if i > len(s)-1: |
| 19 | + # it could potentially be true if the remaining characters are *s |
| 20 | + if p[j:].replace("*","") == "": |
| 21 | + return True |
| 22 | + return False |
| 23 | + if p[j] == '?': |
| 24 | + # If ?, then increment index |
| 25 | + i += 1 |
| 26 | + elif p[j] == '*': |
| 27 | + # If last char in pattern, then true |
| 28 | + if j == len(p)-1: |
| 29 | + return True |
| 30 | + # We want to check all possibilities |
| 31 | + for curr in range(i, len(s)): |
| 32 | + # If the current char is equal to the next char in the pattern or ? |
| 33 | + if s[curr] == p[j+1] or p[j+1] == '?' or p[j+1] == '*': |
| 34 | + if self.isMatch(s[curr:], p[j+1:]): |
| 35 | + return True |
| 36 | + return False |
| 37 | + else: |
| 38 | + # If any char, check char and increment |
| 39 | + if p[j] != s[i]: |
| 40 | + return False |
| 41 | + i += 1 |
| 42 | + return i == len(s) |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +#------------------------------------------------------------------------------ |
| 47 | +# DP Solution |
| 48 | +#------------------------------------------------------------------------------ |
| 49 | +class Solution(object): |
| 50 | + def isMatch(self, s, p): |
| 51 | + """ |
| 52 | + :type s: str |
| 53 | + :type p: str |
| 54 | + :rtype: bool |
| 55 | + """ |
| 56 | + ls = len(s) |
| 57 | + lp = len(p) |
| 58 | + dp = [[False]*(len(p)+1) for i in range(len(s)+1)] |
| 59 | + |
| 60 | + dp[0][0] = True |
| 61 | + |
| 62 | + for i in range(1,len(p)+1): |
| 63 | + if p[i-1] == '*' and dp[0][i-1]: |
| 64 | + dp[0][i] = True |
| 65 | + |
| 66 | + for row in range(1, len(s)+1): |
| 67 | + for col in range(1, len(p)+1): |
| 68 | + if s[row-1] == p[col-1] or p[col-1]=='?': |
| 69 | + dp[row][col] = True and dp[row-1][col-1] |
| 70 | + elif p[col-1] == '*': |
| 71 | + dp[row][col] = dp[row][col-1] or dp[row-1][col-1] or dp[row-1][col] |
| 72 | + return dp[len(s)][len(p)] |
| 73 | + |
| 74 | +#------------------------------------------------------------------------------ |
| 75 | +#Testing |
0 commit comments