LeetCode: Regular Expression Matching
问题描述
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).
Example1
Input: s = “aa”, p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example2
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”.
Example3
Input: s = “ab”, p = “.*”
Output: true
Explanation: " .*" means “zero or more (*) of any character (.)”.
方法思路
采用dp动态规划的方法,分为三部,设置base case(基础情况),update function(迭代函数)以及goal(return value)。base case即考虑一些特殊情况,在update function中的循环遍历中,从子数组向整个数组推进,每次都进行match
代码如下(示例):
/*
dp[i][j] = 比较长度为i的s字符串和长度为j的p字符串是否相等
*/
class Solution {
public boolean isMatch(String s, String p) {
//以长度为基准,所以起始为1
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
//Base case
//字符串s和字符串p的长度都为0,匹配成功
dp[0][0] = true;
//字符串s的长度为0但是p的最后两个字符为x和*,x*可以被看作空,所以只需要比较去掉这两个字符的字符串p
for(int i = 1; i <= p.length(); i++){
if(p.charAt(i-1)=='*' && dp[0][i-2]){
dp[0][i] = true;
}
}
//遍历两个字符串
for(int i = 1; i <= s.length(); i++){
for(int j = 1; j <= p.length(); j++){
//如果s的子串最后一个字符和p子串的最后一个字符都是小写字母并且相等或者p子串的最后一个字符是.
if(s.charAt(i-1) == p.charAt(j-1) ||p.charAt(j-1) == '.'){
dp[i][j] = dp[i-1][j-1];
}
else if(p.charAt(j-1) == '*'){
//p最后两个数表示为x*,s最后一个数表示为y,如果 x != y并且x不是.
if(p.charAt(j-2) != s.charAt(i-1) && p.charAt(j-2) != '.'){
dp[i][j] = dp[i][j-2]; //直接将x*视为空
}
//如果x=y
else{
//存在三种情况,检擦所有三种情况
//1 *表示0个x 这种情况和之前类似 dp[i][j] = dp[i][j-2]
//2 *表示1个x 这种情况可直接忽略*进行比较 dp[i][j] = dp[i][j-1]
//3 *表示多个x 就表示s中最后存在多个x那么先去掉这些x,因为p中的x*可表示为0个
dp[i][j] = (dp[i][j-2] || dp[i][j-1] || dp[i-1][j]);
}
}
}
}
return dp[s.length()][p.length()];
}
}