1. Topic
2. Answers
In backtracking algorithm , we introduce a recursive idea to solve this problem.
In addition, this problem can be solved idea of dynamic programming. We define the state \ (P [i] [j ] \) is the substring \ (s [0, i) \) and \ (p [0, j) \) matches, to match is true, otherwise it is false, then the state transition equation can be divided into the following three cases:
-
- If
p[j-1] != ‘*’ && (s[i-1] == p[j-1] || p[j-1] == ‘.’)
, two characters match the current description and not encounter \ ( '*' \) , then the timeP[i][j] = P[i-1][j-1]
, i.e. when the \ (s [0, i- 1) \) and \ (p [0, j- 1 ) \) match, the \ (s [0, i) \) and \ (p [0, j) \) can match;
- If
-
- If
p[j-1] == ‘*’
, shows that the current character is \ ( '*' \) , and we use it to match zero characters, thenP[i][j] = P[i][j-2]
, i.e. when the \ (s [0, i) \) and \ (p [0, j- 2) \ ) match is skipped \ (p [j-2] , p [j-1] \) after the two elements \ (s [0, i) \) and \ (p [0, j) \) can match;
- If
-
- If
p[j-1] == ‘*’
, as described current character \ ( '*' \) , and we use it to match at least one character, and need to meets[i-1] == p[j-2] || p[j-2] == ‘.’
, thenP[i][j] = P[i-1][j]
, i.e. when the \ (s [0, i- 1) \) and \ (P [ 0, j) \) match, we use the \ ( '*' \) to match \ s [i-1] \ () after, \ (S [0, I) \) and \ (p [0, j) \) will also be able to match. At least one mean here \ ( '*' \) has been used once, but in front of \ (s [0, i- 1) \) and \ (p [0, j) \) matching may also be used .
- If
2 and 3 which can only meet a match, as follows.
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size();
int n = p.size();
vector<bool> temp(n+1, false);
vector<vector<bool> > dp(m+1, temp);
dp[0][0] = true;
for (int j = 1; j <= n; j++)
if (p[j - 1] == '*')
dp[0][j] = dp[0][j-2];
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (p[j - 1] == '*')
{
bool repeat_zero = false;
bool repear_one_more = false;
repeat_zero = dp[i][j - 2];
if (s[i - 1] == p[j - 2] || p[j - 2] == '.')
repear_one_more = dp[i - 1][j];
dp[i][j] = repeat_zero || repear_one_more;
}
else
{
if (s[i - 1] == p[j - 1] || p[j - 1] == '.')
dp[i][j] = dp[i-1][j-1];
}
}
}
return dp[m][n];
}
};
For more exciting, please pay attention to "seniusen"!