题目:
- 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).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
思路:
- 对于
isMatch("abab", ".*ab")
,由于.*
可以匹配空,也可以匹配ab,可能性较多,使用动态规划解决比较合适。 - 子问题很清楚,就是找出子字符串是否匹配。
- 状态转移如下(a代表某一字符,b代表某一非a字符,x代表a后面的字符串,~代表正则后面的字符串。)
\ | 字符串格式 | 正则格式 | 下一状态字符串 | 下一状态正则 | 示例 |
---|---|---|---|---|---|
情况一 | ax | a*~ 或.*~ | ax | ~ | isMatch(“ab”,”a*ab”) |
x | a*~ 或.*~ | isMatch(“aa”,”a*”) | |||
情况二 | ax | b*~ | ax | ~ | isMatch(“aa”,”b*aa”) |
情况三 | ax | a~或.~ | x | ~ | isMatch(“ab”,”.b”) |
情况四 | ax | b~ | false | false | isMatch(“aa”,”ba”) |
代码:
public boolean isMatch(String s, String p) {
//s或p为空时
if("".equals(s)&&"".equals(p))return true;//两者都是空,匹配成功
if("".equals(s)&&p.length()>=2&&"*".equals(p.substring(1,2)))return isMatch(s,p.substring(2));//字符串已经空了,正则要能与空匹配
if("".equals(s)||"".equals(p))return false;//其他情况某一种为空,匹配失败。
//s不为空时
String item = s.substring(0,1);
String rest = s.substring(1);
//情况一
if(p.startsWith(".*")||p.startsWith(item+"*")){
return isMatch(s,p.substring(2))||isMatch(rest,p);
}
//情况二
if(p.length()>=2&&"*".equals(p.substring(1,2))){
return isMatch(s,p.substring(2));
}
//情况三
if(p.startsWith(".")||p.startsWith(item)){
return isMatch(rest,p.substring(1));
}
//情况四
return false;
}
改进:
- 使用递归替换迭代。(原来由后向前,现在由前向后)
- 使用二维动态规划,二维数组保存中间状态,防止重复计算。
- 对于正则字符串,每次也只读取一个字符。之前的做法需要把*和前面的字符一起考虑。
例子:isMatch(“b”,”a*b”),有dp矩阵如下
dp | 0 | 1 | 2 | 3 |
---|---|---|---|---|
0 | true | false | true | false |
1 | false | false | false | true |
特征:
1. dp[0][0]=true;
2. dp[n][0]=false;n>0
3. dp[0][2n-1]=false;n>0
4. dp[0][2n]=p[2n]==*?dp[0][2n-2]:false;n>0
5. dp[i][j]=function(){
if((p[j]==s[i]||p[j]=='.'))return dp[i-1][j-1];
if(p[j]=='*'){
if((p[j-1]!=s[i])&&p[j-1]!='.') {
//*前的字符和当前待匹配字符不一致,此*代表出现0次。
return dp[i][j-2];
} else {
//*代表出现1次或出现>1次或出现0次
return (dp[i][j-1] || dp[i-1][j] || dp[i][j-2]);
}
}
}
代码:
public boolean isMatch(String s, String p) {
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
dp[0][0]=true;
for (int i = 1; i < p.length(); i+=2) {
if (p.charAt(i) == '*' && dp[0][i-1]) {
dp[0][i+1] = true;
}
}
for (int i = 0 ; i < s.length(); i++) {
for (int j = 0; j < p.length(); j++) {
if(p.charAt(j) == '.'||p.charAt(j) == s.charAt(i)){
dp[i+1][j+1]=dp[i][j];
}
if (p.charAt(j) == '*') {
if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) != '.') {
dp[i+1][j+1] = dp[i+1][j-1];
} else {
dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
}
}
}
}
return dp[s.length()][p.length()];
}