10.表达式匹配(Regular Expression Matching)
给定参数字符串s和匹配表达式p,实现支持 . 和 * 的表达式匹配,需要匹配整个字符串(而不是其中一部分)。
说明
- 字符串s可以为空,可以只包含小写字母a-z。
- 匹配表达式p可以为空,可以只包含小写字母a-z,也可以是 . 或 * 。
例子1
- 输入: s=“aa” p=“a”
- 输出: false
- 说明: 匹配表示式"a"没有匹配到整个字符串"aa"
例子2
- 输入: s=“aa” p=“a*”
- 输出: true
- 说明: ’ * ‘表示有0个或以上的’a’。所以,重复’a’一次,就等于’aa’。所以返回结果为true。
例子3
- 输入: s=“ab” p=".* "
- 输出: true
- 说明: ’ . ‘表示有0个或以上的可以匹配任何字符的’* ’ 。
例子4
- 输入: s=“aab” p=“c* a* b”
- 输出: true
- 说明: c可以是0个,a重复一次。所以可以匹配到字符串"aab"。
例子5
- 输入: s=“mississippi” p=“mis* is* p*”
- 输出: true
public static bool IsMatch(string s, string p)
{
if (string.IsNullOrEmpty(p)) return string.IsNullOrEmpty(s);
bool first_match = (!string.IsNullOrEmpty(s) && (p[0] == s[0] || p[0] ==
'.'));
if (p.Length >= 2 && p[1] == '*')
{
return (IsMatch(s, p.Substring(2)) ||(first_match &&
IsMatch(s.Substring(1), p)));
}
else
{
return first_match && IsMatch(s.Substring(1), p.Substring(1));
}
}