[LeetCode] 10. Regular Expression Matching 正則表達式匹配


 

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

 

這道求正則表達式匹配的題和那道 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不為空且首字符匹配(包括 p[0] 為點),調用遞歸函數匹配s和去掉前兩個字符的p(這樣做的原因是假設此時的星號的作用是讓前面的字符出現0次,驗證是否匹配),若匹配返回 true,否則s去掉首字母(因為此時首字母匹配了,我們可以去掉s的首字母,而p由於星號的作用,可以有任意個首字母,所以不需要去掉),繼續進行循環。

- 返回調用遞歸函數匹配s和去掉前兩個字符的p的結果(這么做的原因是處理星號無法匹配的內容,比如 s="ab", p="a*b",直接進入 while 循環后,我們發現 "ab" 和 "b" 不匹配,所以s變成 "b",那么此時跳出循環后,就到最后的 return 來比較 "b" 和 "b" 了,返回 true。再舉個例子,比如 s="", p="a*",由於s為空,不會進入任何的 if 和 while,只能到最后的 return 來比較了,返回 true,正確)。

 

解法一:

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

 

GitHub 同步地址:

https://github.com/grandyang/leetcode/issues/10

 

類似題目:

Wildcard Matching

 

參考資料:

https://leetcode.com/problems/regular-expression-matching/

https://leetcode.com/problems/regular-expression-matching/discuss/5684/9-lines-16ms-c-dp-solutions-with-explanations

https://leetcode.com/problems/regular-expression-matching/discuss/5665/my-concise-recursive-and-dp-solutions-with-full-explanation-in-c

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM