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 lettersa-z
.p
could be empty and contains only lowercase lettersa-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 preceding 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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public boolean isMatch(String s, String p) { 3 int n = s.length(), m = p.length(); 4 boolean [][]f = new boolean[n + 2][m + 2]; 5 f[0][0] = true; 6 for (int j = 1; j <= m; ++j) { 7 for (int i = 0; i <= n; ++i) { 8 if (p.charAt(j - 1) >= 'a' && p.charAt(j - 1) <= 'z') { 9 if (i >= 1 && 10 p.charAt(j - 1) == s.charAt(i - 1) && f[i - 1][j - 1]) { 11 f[i][j] = true; 12 } 13 } else if (p.charAt(j - 1) == '.') { 14 if (i >= 1 && f[i - 1][j - 1]) { 15 f[i][j] = true; 16 } 17 } else if (p.charAt(j - 1) == '*') { 18 if (f[i][j - 1]) f[i][j] = true; 19 if (i >= 1 20 && (p.charAt(j - 2) == '.' 21 ||p.charAt(j - 2) == s.charAt(i - 1) ) 22 && f[i - 1][j - 1]) 23 f[i][j] = true; 24 if (f[i][j - 2]) f[i][j] = true; 25 if (i >= 1 && (p.charAt(j - 2) == '.' || 26 p.charAt(j - 2) == s.charAt(i - 1) ) 27 && f[i - 1][j]) 28 f[i][j] = true; 29 } 30 } 31 } 32 return f[n][m]; 33 } 34 }