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
public class Solution {
public bool IsMatch(string s, string p)
{
if (p.Length == 0)
{
return s.Length == 0;
}
return IsMatch(s, 0, p, 0);
}
/// <summary>
/// 使用双指针, i,j指针处为起点;
/// </summary>
/// <param name="s"></param>
/// <param name="i"></param>
/// <param name="p"></param>
/// <param name="j"></param>
/// <returns></returns>
private bool IsMatch(string s, int i, string p, int j)
{
//p的指针到头了
if (j >= p.Length)
{
//s的指针到头了; 如果两根指针都到头了,也就可以返回true了,表示匹配;
return i >= s.Length;
}
// j < p.Length - 1,为什么-1? ->因为这个分支有*
// p 中下一个是*
if ( j < p.Length - 1 && p.ToCharArray()[j + 1] == '*')
{
while (i < s.Length && compare(s.ToCharArray()[i], s.ToCharArray()[j]))
{
//
if (IsMatch(s, i, p, j + 2))
{
return true;
}
i++;
}
return IsMatch(s, i, p, j + 2);
}
//下一个不是*; s中指针还没到头,而且i和j指针指向的位置相同;
else if (i < s.Length && compare(s.ToCharArray()[i], p.ToCharArray()[j]))
{
//recrusion迭代;
return IsMatch(s, i + 1, p, j + 1);
}
else
{
return false;
}
}
/// <summary>
/// 对比,判断是否属于相同的情况,考虑到.和完全相等;
/// </summary>
/// <param name="c1"></param>
/// <param name="d1"></param>
/// <returns></returns>
public bool compare(char c1, char d1)
{
return d1 == '.' || c1 == d1;
}
}