algorithm procedure
- if the current text character is matching with the pattern character, which means the last character matched, then the result depends on the previous status: res(r,c)=res(r−1,c−1)
- if the current text character is not matching with the pattern character, then result must be false
if the pattern character is
*
, then:- if the pattern character before the current one is not matching with the current text character, which means the current character has 0 occurrence in the
*
pattern, then res(r,c)=res(r,c−2) - if the character before the current pattern character is matching with the text character, which means the text character has one or more occurrence, then res(r,c)=res(r−1,c)
- so the result is:
res(r,c)=res(r,c−2)||(res(r−1,c)(ifcharmatches)
- if the pattern character before the current one is not matching with the current text character, which means the current character has 0 occurrence in the
example table
text = "aa", pattern = ".*", output = true
0 | . | * |
---|---|---|
0 | T | F |
a | F | T |
a | F | F |
text = "aab", pattern = "c*a*b", output = true
0 | c | * | a | * | b |
---|---|---|---|---|---|
0 | T | F | T | F | T |
a | F | F | F | T | T |
a | F | F | F | F | T |
b | F | F | F | F | F |
code
class Solution {
private:
bool charMatch(char s, char p) {
return (s == p) || (p == '.');
}
public:
bool isMatch(string s, string p) {
int R = s.length() + 1, C = p.length() + 1;
vector<vector<bool>> res(R, vector<bool>(C, false));
res[0][0] = true;
for (int c = 1; c < C; ++c) {
if (p[c-1] == '*') {
res[0][c] = res[0][c-2];
}
}
for (int r = 1; r < R; ++r) {
for (int c = 1; c < C; ++c) {
if (charMatch(s[r-1], p[c-1])) {
res[r][c] = res[r-1][c-1];
} else if (p[c-1] == '*') {
res[r][c] = res[r][c-2];
if (charMatch(s[r-1], p[c-2])) {
res[r][c] = res[r][c] || res[r-1][c];
}
} else {
res[r][c] = false;
}
}
}
return res[s.length()][p.length()];
}
};