LeetCodeOJ——10. Regular Expression Matching

来源:互联网 发布:微信营销游戏源码 编辑:程序博客网 时间:2024/05/20 07:59

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

解题思路:
首先注意题目给出的例子isMatch(“aab”, “c*a*b”) → true,之所以aab”和”c*a*b”匹配,是因为c*代表0个或多个c而不是1个或多个c。其次,一开始我用基本的线性解法来做,想了半天没有结果,其实当碰到子问题和原问题类似的情况时,应该要想到递归,最后在网上搜到了答案http://blog.csdn.net/hopeztm/article/details/7992253。自己也按照提示也了一遍:

class Solution {public:    bool isMatch(string s, string p) {        int i=0,j=0;        return recurMatch(s,p,i,j);    }    bool recurMatch(string &s,string &p,int i,int j){        if(j==p.length())            return i==s.length();        if(j+1<p.length()&&p[j+1]=='*'){            while(i<s.length()&&(p[j]==s[i]||p[j]=='.')){                if(recurMatch(s,p,i,j+2))                    return true;                i++;            }            return recurMatch(s,p,i,j+2);        }else{            if(s[i]==p[j]||(p[j]=='.'&&i<s.length())){                if(recurMatch(s,p,i+1,j+1))                    return true;            }            return false;        }    }};
0 0
原创粉丝点击