您的位置:首页 > 其它

Leetcode 10. Regular Expression Matching

2016-10-06 04:05 295 查看
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;
        }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode