PHP - regular expression match

Give you a character string s and a law p, invite you to implement a support '' and '*' in the regular expression matching.

'.' Matches any single character
'*' matches zero or more of the preceding element that a
so-called matching, to cover the entire string s, and not part of the string.

Description:

s may be empty, and only lowercase letters az from the.
p may be empty and contain only lowercase letters from az, and characters. and *.
Example 1:

Input:
S = "AA"
P = "A"
Output: false
interpretation: "a" can not match the entire string "aa".
Example 2:

Input:
S = "AA"
P = "A *"
Output: true
explanation: because the '*' matches zero or representatives of the foregoing that a plurality of elements, this is in front of the element 'a'. Thus, the string "aa" may be regarded as 'a' is repeated once.
Example 3:

Input:
S = "ab &"
P = "*."
Output: true
explained: ". *" Denotes zero or more matches ( '*') of any character ( '.').
Example 4:

Input:
S = "AAB"
P = "C * A * B"
Output: true
explanation: because the '*' means zero or more, where 'c' is 0, 'a' is repeated once. So it can match the string "aab".
Example 5:

Input:
S = "Mississippi"
P = "MIS * IS * P *."
Output: false

Source: stay button (LeetCode)

This problem a little difficult, steal someone else's answer

class Solution {

    /**
     * @param String $s
     * @param String $p
     * @return Boolean
     */
    function isMatch($s, $p) {
        if(empty($p)) return empty($s);
        $first_match = !empty($s) && ($p[0]==$s[0] || $p[0]=='.'); 
        if(strlen($p)>=2 && $p[1]=='*'){
            return $this->isMatch($s, substr($p,2)) || ($first_match && $this->isMatch(substr($s,1), $p));
        }else{
            return $first_match && $this->isMatch(substr($s,1), substr($p,1));
        }
    }
}
 
class Solution {

    /**
     * @param String $s
     * @param String $p
     * @return Boolean
     */
    function isMatch($s, $p) {
        $m = strlen($s);
        $n = strlen($p);
        $f = array_fill(0,$m+1,array_fill(0,$n+1,false));
        $f[0][0] = true;
        for($k = 2; $k <= $n; $k++){
            $f[0][$k] = $f[0][$k - 2] && $p[$k - 1] == '*';
        }
        for($i = 1; $i <= $m; $i++){
            for($j = 1; $j <= $n; $j++){
                if($s[$i - 1] == $p[$j - 1] || $p[$j - 1] == '.'){
                    $f[$i][$j] = $f[$i - 1][$j - 1];
                }
                if($p[$j - 1] == '*'){
                    $f[$i][$j] = $f[$i][$j - 2] || 
                    $f[$i - 1][$j] && ($s[$i - 1] == $p[$j - 2] || $p[$j - 2] == '.');
                }
            }
        }
        return $f[$m][$n];
    }

}

Guess you like

Origin www.cnblogs.com/corvus/p/12110088.html