zoukankan      html  css  js  c++  java
  • 10. Regular Expression Matching *HARD*

    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

    1.
    bool isMatch(string s, string p) {
        int ls = s.length(), lp = p.length(), i, j;
        vector<vector<int>> dp(2, vector<int>(lp + 1, 0));
        bool k = 1;
        dp[0][0] = 1; dp[0][1] = 0;
        for (i = 2; i <= lp; i++)
            dp[0][i] = (dp[0][i - 2] && (p[i - 1] == '*'));
        for (i = 1; i <= ls; i++)
        {
            dp[k][0] = 0;
            for (j = 1; j <= lp; j++)
            {
                if('*' == p[j-1] && j > 1)
                {
                    if(p[j-2] == s[i-1] || '.' == p[j-2])
                        dp[k][j] = dp[k][j-2] | dp[!k][j];
                    else
                        dp[k][j] = dp[k][j-2];
                }
                else if(p[j-1] == s[i-1] || '.' == p[j-1])
                    dp[k][j] = dp[!k][j-1];
                else
                    dp[k][j] = 0;
            }
            k = !k;
        }
        return dp[!k][lp];
    }

    2.

    bool isMatch(string s, string p) {
        int ls = s.length(), lp = p.length(), i, j;
        if(p == "")
            return s == "";
        if(1 == lp || p[1] != '*')
        {
            if(s == "" || (p[0] != '.' && s[0] != p[0]))
                return false;
            return isMatch(s.substr(1), p.substr(1));
        }
        //p[1] == '*'
        for(i = -1; i < ls && (-1 == i || '.' == p[0] || s[i] == p[0]); i++ )
        {
            if(isMatch(s.substr(i+1), p.substr(2)))
                return true;
        }
    }
  • 相关阅读:
    继承
    反射
    DOS使用笔记
    [LeetCode] Merge Intervals
    [LeetCode] Insert Interval
    [LeetCode] Permutation Sequence
    [LeetCode] Rotate List
    [LeetCode] Text Justification
    [LeetCode] Simplify Path(可以不用看)
    [LeetCode] Edit Distance(很好的DP)
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5249558.html
Copyright © 2011-2022 走看看