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".

答案

class Solution {
    public boolean isMatch(String ss, String pp) { 
        int m = ss.length(), n = pp.length();
        char[] A = ss.toCharArray(), B = pp.toCharArray();
        boolean[][] f = new boolean[m + 1][n + 1];

        for(int i = 0; i <= m; i++) {
            for(int j = 0; j <= n; j++) {
                if(i == 0 && j == 0) {
                    f[i][j] = true;
                    continue;
                }
                if(j == 0) {
                    f[i][j] = false; 
                    continue;
                }
                
                f[i][j] = false;
                // Normal character in A matching normal character in B
                // Or normal character in A matching a "." in B
                if(i > 0 && (A[i - 1] == B[j - 1] || B[j - 1] == '.')) {
                    f[i][j] = f[i - 1][j - 1];
                }
                
                if(B[j - 1] == '*') {
                    // A decides to ignore the .* in B
                    f[i][j] = f[i][j] || f[i][j - 2];
                    
                    // A decides to match .* with the last char (if A's last char match with the B's char before *)
                    if(i > 0 && (A[i - 1] == B[j - 2] || B[j - 2] == '.'))
                        f[i][j] = f[i][j] || f[i - 1][j];
                }
                
            }        
        }
        return f[m][n];
    }
}

你可能感兴趣的:(Regular Expression Matching)