LeetCode 10. Regular Expression Matching

来源:互联网 发布:淘宝怎么看买家秀 编辑:程序博客网 时间:2024/06/16 09:25

题目

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


思路

这道题目要求是说:’.’ 代表任意单个字符,’*’ 代表零个或多个前序元素,匹配要覆盖整个字符串,而不能是一部分。
是说,函数bool isMatch(const char *s, const char *p),字符串s能用字符串p的某一子串来表示就返回true,否则返回false。
利用动规来解决这个问题的话,f[i][j]表示到s的前i个字符和p的前j个字符是否可以匹配,结果用true/false表示。
1. 当p[j]==’.’或者s[i]==p[j]时,s的第i个字符与p的第j个字符匹配,f[i+1][j+1]的状态与f[i][j]相同,则有f[i+1][j+1] = f[i][j]
2. 当p[j]==’ * ‘时,这种情况会比较复杂,’ * ‘表示零个或多个前序元素,说明p[j-1]可以出现任意次:
1)p[j-1]出现0次时,f[i+1][j+1]的结果可以取决于f[i+1][j-1],只要f[i+1][j-1] == true,则f[i+1][j+1]=true
2)p[j-1]出现一次时,f[i+1][j+1]的结果也可以取决于f[i+1][j],此时,f[i+1][j+1] = f[i+1][j]
3)p[j-1]出现大于一次时,f[i+1][j+1]的结果也可以取决于f[i][j+1],此时,f[i+1][j+1] = f[i][j+1]

其中需要处理的边界值有:
1.f[0][0] = true。当s和p都为空串时,返回true。
2.f[0][j+1],只有当p[j]=*时取决于f[0][j-1],否则都为false。
3.f[i+1][0]=false


代码

class Solution {public:    bool isMatch(string s, string p) {        vector<vector<bool>> f(s.size()+1,vector<bool>(p.size()+1,false));        f[0][0] = true;        for(int j=1;j<p.size();j++)            f[0][j+1] = p[j] == '*'?f[0][j-1]:false;        for(int i=0;i<s.size();i++)        {            f[i+1][0] = false;            for(int j = 0;j<p.size();j++)            {                if(p[j]=='*')                {                    f[i+1][j+1] = f[i+1][j-1] || (f[i][j+1] && (s[i] == p[j - 1] || p[j - 1] == '.'));                }                else                     f[i+1][j+1] = f[i][j] && (s[i] == p[j] || p[j] == '.');              }        }        return f[s.size()][p.size()];    }};
原创粉丝点击