Regular Expression Matching
Total Accepted: 39732 Total Submissions: 192279Implement 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
[思路]
字符串match, 因为涉及到*可以match 0到多个字符, 必然有backtracking. 再backtracking的过程中, 如果重复, 可以pruning, memo, dynamic programming 进行优化.
[CODE]
1. backtracking
public class Solution {
public boolean isMatch(String s, String p) {
if(p.length()==0) return s.length()==0;
else if(s.length()==0) {
if(p.length()>1 && p.charAt(1)=='*') return isMatch(s, p.substring(2));
else return false;
} else if(p.length()>1 && p.charAt(1)=='*') {
if(isMatch(s,p.substring(2))) return true;
else if(s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') {
return isMatch(s.substring(1), p);
} else {
return false;
}
} else {
return (s.charAt(0)==p.charAt(0) || p.charAt(0)=='.') && isMatch(s.substring(1), p.substring(1));
}
}
}
613




被折叠的 条评论
为什么被折叠?



