题目描述(Hard)
Given an input string (s) and a pattern (p), 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 *.
题目链接
https://leetcode.com/problems/longest-palindromic-substring/description/
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 = "c*a*b"
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 = "mis*is*p*."
Output: false
算法分析
提交代码:
class Solution {
public:
bool isMatch(string s, string p) {
return isMatchCore(s.c_str(), p.c_str());
}
bool isMatchCore(const char *str, const char *pattern)
{
if (*str == '\0' && *pattern == '\0') return true;
if (*str != '\0' && *pattern == '\0') return false;
if (*(pattern + 1) == '*')
{
if (*str == *pattern || (*pattern == '.' && *str != '\0'))
return isMatchCore(str + 1, pattern)
|| isMatchCore(str, pattern + 2)
|| isMatchCore(str + 1, pattern + 2);
else
return isMatchCore(str, pattern + 2);
}
if (*str == *pattern || (*pattern == '.' && *str != '\0'))
return isMatchCore(str + 1, pattern + 1);
return false;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, string str, string p, bool expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName);
Solution s;
bool result = s.isMatch(str, p);
if(result == expected)
printf("passed\n");
else
printf("failed\n");
}
int main(int argc, char* argv[])
{
Test("Test1", string("aa"), string("a"), false);
Test("Test2", string("aa"), string("a*"), true);
Test("Test3", string("ab"), string(".*"), true);
Test("Test4", string("aab"), string("c*a*b"), true);
Test("Test5", string("mississippi"), string("mis*is*p*."), false);
return 0;
}