Created
October 1, 2015 02:40
-
-
Save junjiah/cbef90c41b3407440c76 to your computer and use it in GitHub Desktop.
solved 'Regular Expression Matching' on LeetCode https://leetcode.com/problems/regular-expression-matching/
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
#include <cassert> | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
bool isMatch(string s, string p) { | |
int s_len = s.size(), p_len = p.size(); | |
vector<vector<bool>> matched(p_len + 1, vector<bool>(s_len + 1, false)); | |
matched[0][0] = true; | |
for (int i = 1; i <= p_len; ++i) { | |
// Match sub string until i-th of p. | |
if (p[i - 1] != '*') { | |
for (int j = 1; j <= s_len; ++j) { | |
matched[i][j] = | |
matched[i - 1][j - 1] && (p[i - 1] == '.' || p[i - 1] == s[j - 1]); | |
} | |
} else { | |
// Init the first matching record in case the second char of p is '*'. | |
if (i == 2) { | |
matched[i][0] = true; | |
} else { | |
matched[i][0] = matched[i - 2][0]; | |
} | |
// Wildcard matching begins. | |
for (int j = 1; j <= s_len; ++j) { | |
matched[i][j] = | |
matched[i - 2][j] || | |
(matched[i][j - 1] && (p[i - 2] == s[j - 1] || p[i - 2] == '.')); | |
} | |
} | |
} | |
return matched[p_len][s_len]; | |
} | |
int main() { | |
// Simple test cases. | |
assert(isMatch("aa", "aa")); | |
assert(isMatch("aa", "a*")); | |
assert(isMatch("aa", ".*")); | |
assert(isMatch("aa", "ab*a")); | |
assert(!isMatch("aa", "ab")); | |
assert(isMatch("aa", "c*a*b*")); | |
assert(!isMatch("ab", ".*c")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment