1. 程式人生 > >LeetCode題解--10. Regular Expression Matching

LeetCode題解--10. 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

正則表示式匹配,
. 匹配任何一個簡單字元
*可以匹配零個或者多個任意字元
判斷給定的兩個字元是否匹配

分析

  • 偷懶的方法是直接用語言自帶的正則實現。(Python 又是一句話 =w=)

  • 用 DFS 的方法

  • 可以用 DP 的方法

用陣列 DP :dp[i][j] 表示 s[0..i] 和 p[0..j] 是否 match,當 p[j] != ‘‘,b[i + 1][j + 1] = b[i][j] && s[i] == p[j] ,當 p[j] == ‘’ 要再分類討論,具體可以參考 DP C++,還可以壓縮下把 dp 降成一維:參考這裡
用記憶化,就是把算過的結果儲存下來,下次就不用再算了

Python

import re

class Solution:
    # @return a boolean
    def isMatch(self, s, p)
:
return re.match('^' + p + '$', s) != None # debug s = Solution() print s.isMatch("aa", "a*")

分治–類似與深度優先搜尋DFS

我們會分治搜尋的方法來檢視,

  • 考慮特殊情況即*s字串或者*p字串結束。

    1. s字串結束,要求*p也結束或者間隔‘’ (例如p=”a*b*c……”),否則無法匹配

    2. *s字串未結束,而*p字串結束,則無法匹配

  • *s字串與*p字串均未結束

    1. (p+1)字元不為’‘,則只需比較s字元與*p字元,若相等則遞迴到(s+1)字串與*(p+1)字串的比較,否則無法匹配。

    2. (p+1)字元為’‘,則p字元可以匹配*s字串中從0開始任意多(記為i)等於*p的字元,然後遞迴到(s+i+1)字串與*(p+2)字串的比較,

只要匹配一種情況就算完全匹配。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>



#define __tmain main

///if      p[j+1] == '*' -> (i + 1, j + 1)
///else if p[i] == p[j] -> (i + 1, j + 2) or (i, j+2)
///else -> (i, j+2)

bool isMatch(const char *s, const char *p)
{
    if (*p == '\0')         //  正則p到底末尾時
    {
        return !(*s);       //  如果串s頁到達末尾,則匹配成功
    }

    int slen = strlen(s), plen = strlen(p);

    if (plen == 1           //  如果正則串只有一個長度
    || *(p + 1) != '*')     //  如果匹配×
    {
        return slen && (p[0] == '.' || *s == *p)
            && isMatch(s + 1, p + 1);
    }
    else
    {
        while (*s != '\0' && (*p == '.' || *s == *p))
        {

            if (isMatch(s++, p + 2))
            {
                return true;
            }
        }

    }

    return isMatch(s, p + 2);

}


動態規劃

dp[i][j] 表示 s[0..i] 和 p[0..j] 是否 match,

  • 當 p[j] != ‘*’,b[i + 1][j + 1] = b[i][j] && s[i] == p[j] ,

  • 當 p[j] == ‘*’ 要再分類討論,具體可以參考 DP C++,還可以壓縮下把 dp 降成一維:

下面是那位大神的程式碼

class Solution {
public:
    bool isMatch(string s, string p) {
        /**
         * f[i][j]: if s[0..i-1] matches p[0..j-1]
         * if p[j - 1] != '*'
         *      f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1]
         * if p[j - 1] == '*', denote p[j - 2] with x
         *      f[i][j] is true iff any of the following is true
         *      1) "x*" repeats 0 time and matches empty: f[i][j - 2]
         *      2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j]
         * '.' matches any single character
         */
        int m = s.size(), n = p.size();
        vector<vector<bool>> f(m + 1, vector<bool>(n + 1, false));

        f[0][0] = true;
        for (int i = 1; i <= m; i++)
            f[i][0] = false;
        // p[0.., j - 3, j - 2, j - 1] matches empty iff p[j - 1] is '*' and p[0..j - 3] matches empty
        for (int j = 1; j <= n; j++)
            f[0][j] = j > 1 && '*' == p[j - 1] && f[0][j - 2];

        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++)
                if (p[j - 1] != '*')
                    f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '.' == p[j - 1]);
                else
                    // p[0] cannot be '*' so no need to check "j > 1" here
                    f[i][j] = f[i][j - 2] || (s[i - 1] == p[j - 2] || '.' == p[j - 2]) && f[i - 1][j];

        return f[m][n];
    }
};