Regular Expression Matching
Given an input string (s) and a pattern §, implement regular expression matching with support for ‘.’ and ‘*’.
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
Input:
s = “aa”
p = “a*”
Output: true
Explanation: ‘*’ means zero or more of the precedeng element, ‘a’. Therefore, by repeating ‘a’ once, it becomes “aa”.
Example 3:
Input:
s = “ab”
p = “."
Output: true
Explanation: ".” means “zero or more (*) of any character (.)”.
Example 4:
Input:
s = “aab”
p = “cab”
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches “aab”.
Example 5:
Input:
s = “mississippi”
p = “misisp*.”
Output: false
题目解读:就是星号(*)代表星号前面的字符可重复0到n次;点号(.)代码任何字符。
题目代码:
class Solution {
public:
bool isMatch(string s, string p) {
if(p.empty())
{
return s.empty();//s为空,true;
}
if(p.size() > 1 && p[1] == '*')//p的第二个字符为*
{
return isMatch(s, p.substr(2)) || (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p));
//此时有二种情况:1.p的第一个字符的重复次数为0,因为p的第二个字符为*,所以p从第三个字符与s递归比较;
2.s与p的第一个字符相等,即(s[0] == p[0] || p[0] == '.'),同时满足s从第二个字符开始与p第一个字符开始比较,不是与p的第二个字符
比较是因为p[1] == '*',p的第一个字符可以有多个。
}
else
{
return !s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p.substr(1));
}
}
};
普及下:string.substr(index),即表示从下标index开始至字符串末尾的字符串,例如 hello.substr(1) == ello;
解题思路:通过从首字母开始比较,然后采用递归的方式向后进行递归比较,字符串向后截取采用了substr的函数,这个是关键。
性能:
总结:二个字符串从头开始递归比较,算是暴力破解,性能不佳,欢迎大家提供更好的思路。
LeetCode今天刷到了第十题,收获颇多,思维开拓不少,继续加油!