1. 程式人生 > >leetcode -10. Regular Expression Matching

leetcode -10. Regular Expression Matching

logs bsp ret subst || lee match empty 三種

技術分享

三種情況:

“a” 對應"a",

"." 對應 "a"

"a*" 對應 “aa”

當p為空,s為空時可以匹配;

若p的第二個字符為*,第一情況為不匹配(b, a*b);從 (b,b)開始匹配

第二種情況為匹配(a, a*); 首元素相同, 從( ,a*)開始匹配

若p的第二個字符不為*, 首字符必須要匹配, 再對首字符後的字符串匹配

recursive solution:

class Solution {
public:

    
    bool isMatch(string s, string p) {
        
if(p.empty()) return s.empty(); // if(s.empty()) return p.empty(); if(p[1]==*) { return (isMatch(s,p.substr(2))||((p[0]==s[0]||p[0]==.)&&!s.empty()&&isMatch(s.substr(1),p))); // if(p[0]==s[0]||p[0]==‘.‘&&!s.empty()) // return isMatch(s.substr(1),p);
// else // return isMatch(s,p.substr(2)); } else { if(p[0]==s[0]||p[0]==.&&!s.empty()) return isMatch(s.substr(1),p.substr(1)); else return false; //return (p[0]==s[0]||p[0]==‘.‘)&&!s.empty()&&isMatch(s.substr(1),p.substr(1));
} } };

DP solution:

定義如果 dp[i+1][j+1]匹配,當s[0-i]與p[0-j]匹配。

如果 p[j]!=‘*‘, dp[i][j]=dp[i-1][j-1] && s[i-1]==p[j-1];

如果p[j]==‘*‘, dp[i][j]==dp[i][j-2], 0times repeat

dp[i][j]==dp[i-1][j]&& (s[i - 1] == p[j - 2] || p[j - 2] == ‘.‘)the pattern repeats for at least 1 times.

leetcode -10. Regular Expression Matching