Regular Expression Matching:仿正则匹配字符串

来源:互联网 发布:jsp中注释java代码 编辑:程序博客网 时间:2024/06/05 18:56

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
思路:难点在于这种情况:

“aaa“ “ab*a*c*a* ”即你不知道中间的a*是匹配了一次,多次,还是压根就没匹配,所以这些种情况都要考虑。

思路动态规划,d[i][j]表示s长度i能否匹配p长度j 

1, If p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];

2, If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];

3, If p.charAt(j) == '*': here are two sub conditions:  

1 if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty  

2 if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':  

dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a  

or dp[i][j] = dp[i][j-1] // in this case, a* counts as single a  

or dp[i][j] = dp[i][j-2] // in this case, a* counts as empty

class Solution {    public boolean isMatch(String s, String p) {        if(s==null||p==null) return false;        boolean[][] d = new boolean[s.length()+1][p.length()+1];        d[0][0] = true;//因为长度0匹配长度0一定可以匹配上        for(int i = 0;i<p.length();i++){//扫描p初始化,对于s.length==0来说,只有如a*,a*b*这种一个字母对应一个*的才能完全匹配。            if(p.charAt(i)=='*'&&d[0][i-1]){//字符串位置i对应d中的i+1,所以对于i:d[i-1]对应前一个非*字母在d中的位置,d[i+1]对应字符i在d[]中的位置。 d[]0[i-1]表示到前一个非*字母位置都能匹配                d[0][i+1] = true;            }        }        for(int i = 0;i<s.length();i++){            for(int j=0;j<p.length();j++){                if(p.charAt(j)=='.'){                    d[i+1][j+1] =d[i][j];                }                if(s.charAt(i)==p.charAt(j)){                    d[i+1][j+1] =d[i][j];                }                if(p.charAt(j)=='*'){                    if(p.charAt(j-1)!='.'&&p.charAt(j-1)!=s.charAt(i)){                        d[i+1][j+1] = d[i+1][j-1];                    }else{                        d[i+1][j+1] = (d[i][j+1]||d[i+1][j]||d[i+1][j-1]);                    }                                    }            }                    }             return d[s.length()][p.length()];    }    }





阅读全文
0 0
原创粉丝点击