The match should cover the entire string (s), not part of the string.
Explain:
s may be empty and contain only lowercase letters from a-z.
p may be empty and contain only lowercase letters from a-z, as well as the characters. And *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: 'a' cannot match the entire string of 'aa'.
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means that zero or more preceding elements can be matched, that is, 'a' can be matched. Therefore, repeat 'a' once and the string can be changed to 'aa'.
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ". *" means that zero or more ('*') arbitrary characters ('.') can be matched.
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: 'c' may not be repeated, and 'a' may be repeated once. So you can match the string "aab.".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
Idea: if s and p match, just compare them one by one, mainly dealing with *
#include <iostream> #include <vector> using namespace std; bool isMatch(string s, string p) { // ans[i][j]==true Express s Before i Bit sum p Before j Bits are matched vector< vector<bool> > ans(s.length() + 3, vector<bool>(p.length() + 3, false)); ans[0][0] = true;//It's all zero, of course it matches ans[1][1] = s[0] == p[0] || p[0] == '.';//If the lengths are all 1, they are either equal or p by. for (int j = 2; j < p.length() + 1; j += 2) //ans[0][j - 2]Is the previous position, j-1 Is the current location ans[0][j] = ans[0][j - 2] && p[j - 1] == '*';//When s Empty, required p Only like a*b*c*d*This form can be successfully matched because*You can set the front to 0 for (int i = 1; i < s.length() + 1; i++)//s Is the determined string for (int j = 2; j < p.length() + 1; j++)//p The string is to be traversed { if (p[j - 1] != '*') ans[i][j] = ans[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.'); else /*The current position is *, so there are two situations to consider, *1.If the i-th bit of s matches the j-1 st bit of p, that is, ans [i-1] [J], then * performs the operation of copying the previous character, and the i-1st bit of s must match the j-th bit of p at this time *2.If the previous bit does not match, the operation to clear the previous character is performed. At this time, I bit and the first j-2 bit are matched. ans[i][j - 2] * */ ans[i][j] = ans[i][j - 2] || ans[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'); } return ans[s.length()][p.length()]; } int main() { string s="ab"; string p=".*"; std::cout <<isMatch(s,p)<< std::endl; return 0; }