正则表达式匹配
剑指offer原题: 思路,回溯,关键是处理下一个字符是“*”的情况,如果下一个字符是“*”,且当前字符匹配(下一个字符是“*”,当前不匹配只有一种情况),分三种情况讨论: 代码如下: public boolean match(char[] str,char[] pattern) {
if(str==null || pattern==null){return false;}
return matchCore(str,pattern,0,0);
}
public boolean matchCore(char[] str,char[] pattern,int i,int j){
if(i==str.length && j==pattern.length){ //同时到达终点
return true;
}
//pattern已经到达终点,没有伸缩的可能,如果str先到达终点,但是pattern后面时*号的话还是有可能仍然成立的
if(i<str.length && j==pattern.length){
return false;
}else if(i==str.length){
return chechNull(pattern,j);
}
if(j+1<pattern.length && pattern[j+1]=='*'){ //模式后一个是*号
if(str[i]==pattern[j] ||(pattern[j]=='.' && i<str.length)){
boolean res = matchCore(str,i+1,j+2) || matchCore(str,i,j);
return res;
}else{
return matchCore(str,j+2);//不匹配,只能把*当做出现零次
}
}
if(str[i]==pattern[j] ||(pattern[j]=='.' && i<str.length)){
return matchCore(str,j+1);
}
return false;
}
//用于源字符串检测完了,判断模式字符串后面是不是空串
public boolean chechNull(char[] pattern,int j){
if(pattern[pattern.length-1] !='*'){
return false;
}
for(int k=j;k<pattern.length;k++){
if(pattern[k]!='*' && k+1<pattern.length && pattern[k+1]!='*'){
return false;
}
}
return true;
}
leetcode上有一个题跟这个类似, Implement wildcard pattern matching with support for ‘?’ and ‘*’. The matching should cover the entire input string (not partial). The function prototype should be: Some examples: https://leetcode.com/problems/wildcard-matching/ 仿照上面的题目写了一下源代码,结果超时,这个题一般使用动态规划。 public boolean isMatch_2d_method(String s,String p) {
int m=s.length(),n=p.length();
boolean[][] dp = new boolean[m+1][n+1];
dp[0][0] = true;
for (int i=1; i<=m; i++) {
dp[i][0] = false;
}
for(int j=1; j<=n; j++) {
if(p.charAt(j-1)=='*'){
dp[0][j] = true;
} else {
break;
}
}
for(int i=1; i<=m; i++) {
for(int j=1; j<=n; j++) {
if (p.charAt(j-1)!='*') {
dp[i][j] = dp[i-1][j-1] && (s.charAt(i-1)==p.charAt(j-1) || p.charAt(j-1)=='?');
} else {
dp[i][j] = dp[i-1][j] || dp[i][j-1];
}
}
}
return dp[m][n];
}
解释如下,其实我也不是很明白: 关键在于理解 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |