10. Regular Expression Matching (JAVA)

时间:2021-01-04 07:07:45

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".
Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng 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

class Solution {
public boolean isMatch(String s, String p) {
return recur(s,p,0,0);
} public boolean recur(String s, String p, int sPtr, int pPtr) {
if(s.length() == sPtr && p.length() == pPtr) return true;
if(p.length() == pPtr) return false;
if(s.length() == sPtr){
if(p.length() > pPtr+1 && p.charAt(pPtr+1)=='*') return recur(s,p,sPtr,pPtr+2);
else return false;
} if(p.length() > pPtr+1 && p.charAt(pPtr+1)=='*'){ //next bit is *
if(recur(s,p,sPtr,pPtr+2)) return true; //* match 0 element
else{
for(int i = 1; sPtr + i <= s.length() && (p.charAt(pPtr)==s.charAt(sPtr+i-1)|| p.charAt(pPtr)=='.'); i++){
if(recur(s,p,sPtr+i,pPtr+2)) return true; //* match i elements
}
}
}
else if(p.charAt(pPtr)=='.' || p.charAt(pPtr)==s.charAt(sPtr))
return recur(s, p, sPtr+1, pPtr+1); return false;
}
}

当当前字符之后的那个字符是*时,我们需要对当前字符做特别判断,所以没次递归中要判断p字符串的下一个字符是否是*