Created
September 30, 2018 14:10
-
-
Save zhangxiaomu01/e13f60b68e369ef4577cf9a865aabfa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isMatch(string s, string p) { | |
int len_s = s.size(), len_p = p.size(); | |
//We only allocate 2 columns, which reduce the space complexity to linear. | |
bool dp[2][len_p+1]; | |
//Since the dp[len_s%2][len_p] means comparison of two empty string, which should be true. | |
dp[len_s%2][len_p] = true; | |
for(int i = len_s; i>= 0; i--){ | |
for(int j = len_p; j>= 0; j--){ | |
//We already set the value to true above; | |
if(i == len_s && j == len_p) continue; | |
bool firstMatch = (i<len_s && j< len_p && (s[i] == p[j] || p[j] == '.')); | |
if(j+1 < len_p && p[j+1] == '*'){ | |
dp[i%2][j] = dp[i%2][j+2]|| (firstMatch&&dp[(i+1)%2][j]); | |
} | |
else | |
dp[i%2][j] = firstMatch&&dp[(i+1)%2][j+1]; | |
} | |
} | |
return dp[0][0]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment