美文网首页ACM题库~
LeetCode 10. Regular Expression

LeetCode 10. Regular Expression

作者: 关玮琳linSir | 来源:发表于2017-09-11 18:23 被阅读17次

10. 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

题意:返回前一个字符串是否满足后面的正则表达式。

c++(动态规划算法):

class Solution {
public:
    bool isMatch(string s, string p) {
        int m = s.size(), n = p.size();
        vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
        dp[0][0] = true;
        for (int i = 0; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (j > 1 && p[j - 1] == '*') {
                    dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
                } else {
                    dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
                }
            }
        }
        return dp[m][n];
    }
};

java(利用系统的正则表达式):

class Solution {
    public boolean isMatch(String s, String p) {
        return s.matches(p);
    } 
}

相关文章

网友评论

    本文标题:LeetCode 10. Regular Expression

    本文链接:https://www.haomeiwen.com/subject/xybfsxtx.html