原题链接:https://leetcode.com/problems/regular-expression-matching
原题内容如下所示:
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).The function prototype should be: bool isMatch(const char *s, const
char *p)Some examples:
isMatch(“aa”,”a”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “a*”) → true
isMatch(“aa”, “.*”) → true
isMatch(“ab”, “.*”) → true
isMatch(“aab”, “c*a*b”) → true
题目描述的意思大概是正则表达式的匹配问题,根据之前运用过正则表达式的经验,这种表达式在实际应用中非常实用,可以只用很少的字符、数字和符号来表示一种类型的字符串
这道题主要涉及了“.”,用来表示单个字符,“*”表示0个字符或是任意之前至少一个字符。
要分两种情况,这种类型的题目最先想到的就使用递归的算法来解决,所以我在这里分两种情况,一种是匹配字符串p的第二位是否是“*”,如果是,那么就判断s和p第一位是否相等,s的子字符串的第一位和p是否匹配,s和p的第三位开始的子字符串是否匹配;另外一种情况是直接比较s和p的第一位是否相同,然后再从s和p的第二位开始匹配,通过递归来得到字符串是否匹配的最终结果。
代码如下所示(已AC):
class Solution {
public:
bool isMatch(string s, string p) {
if (p.empty()) return s.empty();
if ('*' == p[1])
return (isMatch(s, p.substr(2)) || !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p));
else
return !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p.substr(1));
}
};