1. 程式人生 > >[LeetCode] Regular Expression Matching 正則表示式匹配

[LeetCode] 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

這道求正則表示式匹配的題和那道 Wildcard Matching 萬用字元匹配的題很類似,不同點在於*的意義不同,在之前那道題中,*表示可以代替任意個數的字元,而這道題中的*表示之前那個字元可以有0個,1個或是多個,就是說,字串a*b,可以表示b或是aaab,即a的個數任意,這道題的難度要相對之前那一道大一些,分的情況的要複雜一些,需要用遞迴Recursion來解,大概思路如下:

- 若p為空,若s也為空,返回true,反之返回false

- 若p的長度為1,若s長度也為1,且相同或是p為'.'則返回true,反之返回false

- 若p的第二個字元不為*,若此時s為空返回false,否則判斷首字元是否匹配,且從各自的第二個字元開始呼叫遞迴函式匹配

- 若p的第二個字元為*,若s不為空且字元匹配,呼叫遞迴函式匹配s和去掉前兩個字元的p,若匹配返回true,否則s去掉首字母

- 返回呼叫遞迴函式匹配s和去掉前兩個字元的p的結果

解法一:

class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        if (p.size() == 1) {
            return (s.size() == 1 && (s[0] == p[0] || p[0
] == '.')); } if (p[1] != '*') { if (s.empty()) return false; return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1)); } while (!s.empty() && (s[0] == p[0] || p[0] == '.')) { if (isMatch(s, p.substr(2))) return true; s = s.substr(1); } return isMatch(s, p.substr(2)); } };

上面的方法可以寫的更加簡潔一些,但是整個思路還是一樣的,我們先來判斷p是否為空,若為空則根據s的為空的情況返回結果。當p的第二個字元為*號時,由於*號前面的字元的個數可以任意,可以為0,那麼我們先用遞迴來呼叫為0的情況,就是直接把這兩個字元去掉再比較,或者當s不為空,且第一個字元和p的第一個字元相同時,我們再對去掉首字元的s和p呼叫遞迴,注意p不能去掉首字元,因為*號前面的字元可以有無限個;如果第二個字元不為*號,那麼我們就老老實實的比較第一個字元,然後對後面的字串呼叫遞迴,參見程式碼如下:

解法二:

class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        if (p.size() > 1 && p[1] == '*') {
            return isMatch(s, p.substr(2)) || (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p));
        } else {
            return !s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));
        }
    }
};

我們也可以用DP來解,定義一個二維的DP陣列,其中dp[i][j]表示s[0,i)和p[0,j)是否match,然後有下面三種情況(下面部分摘自這個帖子):

1.  P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
2.  P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times;
3.  P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times.


解法三:

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];
    }
};

類似題目:

參考資料: