同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为给定两个字符串,第二个字符串为字符串格式,比对两字符串是否相符。
' . ' 代表任意单一字符 , ' * ' 代表前一字符可以为0次出现或任意次数出现。
题目与范例如下
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
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 preceding 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
Constraints:
0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.
解题方法为采用递归策略,如代码所示。
下方为我的代码
bool isMatch(char * s, char * p){
if(strlen(s) == 0 && strlen(p) == 0){
return true;
}
if(strlen(p) > 1 && p[1] == '*'){
if(isMatch(s,&p[2])){
return true;
}
if((p[0] == '.' || s[0] == p[0]) && strlen(s) > 0){
return isMatch(&s[1],p);
}
return false;
}
else{
if((p[0] == '.' || p[0] == s[0]) && strlen(s) > 0){
return isMatch(&s[1],&p[1]);
}
return false;
}
return false;
}
下方为时间与空间之消耗
Runtime: 40 ms, faster than 20.23 % of C online submissions for Regular Expression Matching.
Memory Usage: 5.5 MB, less than 78.61 % of C online submissions for Regular Expression Matching.
本题官方解答还有采用动态规划,可以到 LeetCode上查询。
本文探讨了如何使用递归实现字符串'.'和'*'的正则表达式匹配,通过实例解析规则并提供高效的C++代码。解题方法涉及处理'*'的重复和'.'的任意性,同时满足完全匹配输入字符串的要求。

被折叠的 条评论
为什么被折叠?



