LeetCode C++ 10. Regular Expression Matching【String】困難

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 preceding 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

題意:匹配正則表達式。

思路:遞歸,基準條件是 p空 ,然後匹配第一個字符,接着匹配剩下的字符。

代碼:

class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty(); //p空和s空爲真;p空s非空爲假
        bool firstMatch = !s.empty() && (s[0] == p[0] || p[0] == '.'); //s非空的情況下比較第一個字符

        if (p.size() >= 2 && p[1] == '*') { //匹配s[0]0次或多次 
            return isMatch(s, p.substr(2)) || (firstMatch && isMatch(s.substr(1), p));
        } else 
            return firstMatch && isMatch(s.substr(1), p.substr(1)); //遞歸判斷第二個字符是否匹配
    }
};

效率不高:

執行用時:852 ms, 在所有 C++ 提交中擊敗了9.17% 的用戶
內存消耗:13.3 MB, 在所有 C++ 提交中擊敗了21.43% 的用戶

其實可以用再優化一下代碼,減少字符串的複製和拷貝;或者用動態規劃;或者用AC自動機等等。

這道題還有很多值得挖掘的地方,以後再更新,多做幾次。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章