Skip to main content

10 Regular Expression Matching

Leetcode

Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:

'.' Matches any single character.​​​​
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

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

如果当前元素匹配且下一个元素是星号,可以尝试匹配 1 个,匹配 0 个,匹配多个

class Solution {
public boolean isMatch(String s, String p) {
if(s==null || p==null) return false;
return isMatch(s, p, 0, 0);
}

private boolean isMatch(String s, String p, int i1, int i2){
if(i1==s.length() && i2==p.length()) return true;
if(i2>=p.length() || i1>s.length()) return false;

if(i2+1<p.length() && p.charAt(i2+1)=='*'){
if(p.charAt(i2)=='.' ||
(i1<s.length() && s.charAt(i1)==p.charAt(i2))){
return isMatch(s, p, i1+1, i2+2) ||
isMatch(s, p, i1, i2+2) ||
isMatch(s, p, i1+1, i2);
} else {
return isMatch(s, p, i1, i2+2);
}
}

if(i1<s.length() && s.charAt(i1)==p.charAt(i2) || p.charAt(i2)=='.'){
return isMatch(s, p, i1+1, i2+1);
}

return false;
}

}