您的位置:首页 > 其它

[LeetCode] Regular Expression Matching

2017-06-01 06:19 357 查看
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


递归求解  注意细节
public class Solution {
public boolean isMatch(String s, String p) {
return isMatch(s,0,p,0);
}
public boolean isMatch(String s,int i,String p,int j){
if(j==p.length()) return i==s.length();
if(j==p.length()-1||p.charAt(j+1)!='*'){
if(i==s.length()) return false;
if(compare(s.charAt(i),p.charAt(j))){
return isMatch(s,i+1,p,j+1);
}
return false;
}
else if(p.charAt(j+1)=='*'){
if(isMatch(s,i,p,j+2)) return true;
for(;i<s.length();i++){
if(compare(s.charAt(i),p.charAt(j))){
if(isMatch(s,i+1,p,j+2)) return true;
}else break;
}
return false;
}
return false;
}
public boolean compare(char a,char b){
return a=='.'||b=='.'||a==b;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: