topic
Implement comprises a function to match '' and ' n' of expression. Mode character '.' Represents any one character ' ' is represented in front of the character may be any number of times (including 0 time). In this problem, the match is a whole pattern matches all characters of the string. For example, the string "aaa" mode and "aa" and "ab & AC A" match, but "aa.a" and "ab * a" do not match.
Topic Link
Thinking
Dynamic programming:
DP [i] [j] denotes the first j characters before i-th character of s and p are matched.
Note pit:
1. The beginning of the initialization, in particular dp [0] [m] values.
2. To open up an array bigger.
3. Match 0 really is a giant pit!
Code
class Solution {
public:
bool isMatch(string s, string p) {
int l1 = s.size(),l2 = p.size();
vector<vector<bool> > dp(l1 + 1,vector<bool>(l2 + 1,false));
dp[0][0] = true;
for(int j = 1;j <= l2;j++){
if(p[j - 1] == '*' && j - 2 >= 0) dp[0][j] = dp[0][j - 2];
}
for(int i = 1;i <= l1;i++){
for(int j = 1;j <= l2;j++){
if(p[j - 1] == s[i - 1] || p[j - 1] == '.'){
dp[i][j] = dp[i - 1][j - 1];
}else if(p[j - 1] == '*'){
if(p[j - 2] == s[i - 1] || p[j - 2] == '.')
dp[i][j] = (dp[i - 1][j] || dp[i][j - 2]);
else
dp[i][j] = dp[i][j - 2];
}
}
}
return dp[l1][l2];
}
};