LeetCode第10题 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 '*'
*/
public class RegularExpressionMatching {
public static void main(String[] args) {
String s="ac";
String p="a*c";
RegularExpressionMatching wm = new RegularExpressionMatching();
boolean result = wm.isMatch(s, p);
System.out.println(result);
}
public boolean isMatch(String s, String p) {
if(s!=null&&p==null)
return false;
// 默认值都是false,后面我们只讨论变为true的情况
boolean[][] match=new boolean[s.length()+1][p.length()+1];
// 1. 初始状态
// s、p比较0个字符,自然为true。不是指索引0处的字符串,而是值字符的个数
match[0][0]=true;
for(int i=1;i<=p.length();i++){
// 这里若冲里,表示i>=2,至少要比较前两个字符,*不可能是第一个字符
if(p.charAt(i-1)=='*'){
// 这里的赋值可能是false也可能是true
match[0][i]=match[0][i-2];
}
}
for(int i=1;i<=s.length();i++){
for(int j=1;j<=p.length();j++){
// 2. 状态转移函数
// 下面总体讨论的是,当前p、s是相等的,或者转化后是等效的,或者是消除后是等效的
//若s和p字符相等或者p的字符是'.',则和dp[i-1][j-1]情况一致
// 最简单的情况,看左上角就好
if(s.charAt(i-1)==p.charAt(j-1)||p.charAt(j-1)=='.'){
match[i][j]=match[i-1][j-1];
}else if(p.charAt(j-1)=='*'){
/*
* s的当前和p的*前一个字符是否相等:
* 相等:
* *表示0: match[i][j]=match[i][j-2],直接跳一个判断 abcd abcd*e -> abcd与abcd匹配
* *表示1,2,3,4,5:match[i][j] == match[i-1][j] abcd* abcdd -> ascd*与abcd匹配,abcddd是一样的
* 当前字符不相等,但是p的当前字符是*,则表示p当前的前一个字符与s当前字符相等
* (因为p当前的前一个字符与当前字符相等)
* 不相等:
* *表示0: match[i][j]=match[i][j-2],直接跳一个判断 abcd abcd*e -> abcd与abcd匹配
* *表示1,2,3,4,5: s的当前和p的*一定不相等,因为s的当前和p的*前一个字符不相等,不讨论
* */
if((p.charAt(j-2)==s.charAt(i-1)||p.charAt(j-2)=='.')){
match[i][j]=match[i][j-2]||match[i-1][j];
}else{
match[i][j]=match[i][j-2];
}
//其余情况都是false,默认不变
}
}
}
// 3. 停止条件:循环结束
// 4. 返回
return match[s.length()][p.length()];
}
}