1. 程式人生 > >leetcode-10:Regular Expression Matching正則表示式匹配

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

給定一個字串 (s) 和一個字元模式 (p)。實現支援 '.' 和 '*' 的正則表示式匹配。

'.' 匹配任意單個字元。
'*' 匹配零個或多個前面的元素。

匹配應該覆蓋整個字串 (s) ,而不是部分字串。

說明:

  • s 可能為空,且只包含從 a-z 的小寫字母。
  • p 可能為空,且只包含從 a-z 的小寫字母,以及字元 . 和 *

示例 1:

輸入:
s = "aa"
p = "a"
輸出: false
解釋: "a" 無法匹配 "aa" 整個字串。

示例 2:

輸入:
s = "aa"
p = "a*"
輸出: true
解釋: '*' 代表可匹配零個或多個前面的元素, 即可以匹配 'a' 。因此, 重複 'a' 一次, 字串可變為 "aa"。

示例 3:

輸入:
s = "ab"
p = ".*"
輸出: true
解釋: ".*" 表示可匹配零個或多個('*')任意字元('.')。

示例 4:

輸入:
s = "aab"
p = "c*a*b"
輸出: true
解釋: 'c' 可以不被重複, 'a' 可以被重複一次。因此可以匹配字串 "aab"。

示例 5:

輸入:
s = "mississippi"
p = "mis*is*p*."
輸出: false

思路:用遞迴思路,但是如果寫  這種遞迴,時間不能通過。分為3種情況,1.當模板p為空時,若s也空返回true,否則flase,2.當p的串大於1且p[1]=='*"時, 需要匹配'*',方法有當前s匹配p[2],或者當前元素相等匹配s[1]和p,3.在以上條件不滿足,也就是要麼p==1或p[1]!='*',則只需要匹配當前的s和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));
    }
};