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
(注意 ' * ' 匹配零个或者多个前面的元素 不能单独出现, 第二个string只要有一部分匹配第一个就可以)
这道题有两个case
1. 第二个char不是'*':
判定的第一个元素是否match 然后再递归match后面元素
2. 第二个char是' * '
p元素的第一个元素是. 或者p能匹配第i个元素 然后递归的match s的i+1后面 和p的* 后面元素
specail case p的长度是0 或者1
public class Solution {
public boolean isMatch(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
if (p.length() == 1) {//长度为1是special case
return (s.length() == 1) && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.');
}
if (p.charAt(1) != '*') {// case 1 第二个元素不是*
if (s.length() == 0) {
return false;
} else {
return (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && isMatch(s.substring(1), p.substring(1));
}
} else {// case 2 第二个元素是*
if (isMatch (s, p.substring(2))) {//case2.1 *不代表任何element
return true;
}
int i = 0;
//case2.2 * 代表一个或者多个element
while (i < s.length() && (s.charAt(i) == p.charAt(0) || p.charAt(0) == '.')) {
//因为*可以匹配多个跟前边相同的元素 只要i跟前边相同就可以继续往下找
if (isMatch(s.substring(i + 1), p.substring(2))) {
return true;
}
i++;
}
return false;
}
}
}
没有评论:
发表评论