[LeetCode] Regular Expression Matching
2017-06-01 06:19
357 查看
Implement regular expression matching with support for
递归求解 注意细节
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;
}
}
'.'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;
}
}
相关文章推荐
- [LeetCode] Regular Expression Matching
- LeetCode 142 Regular Expression Matching
- LeetCode Regular Expression Matching
- Leetcode 10 - Regular Expression Matching
- leetcode 10 Regular Expression Matching & 44 Wildcard Matching
- LeetCode Regular Expression Matching
- LeetCode: Regular Expression Matching
- LeetCode Regular Expression Matching 极品代码赏析
- LeetCode Regular Expression Matching
- leetcode 10. Regular Expression Matching
- LeetCode OJ - Regular Expression Matching
- LeetCode -- Regular Expression Matching
- LeetCode 10: Regular Expression Matching
- leetcode-Regular Expression Matching
- Leetcode——44Wildcard Matching && 10 Regular Expression Matchi
- leetcode 10. Regular Expression Matching
- LeetCode-Regular Expression Matching-正则匹配-DP
- [Leetcode]_10 Regular Expression Matching
- Leetcode: Regular Expression Matching
- LeetCode 010-Regular Expression Matching