您的位置:首页 > 其它

LeetCode-10. Regular Expression Matching

2016-05-05 21:11 260 查看
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


这道题好难,,,尝试了几种方法,都不能包括所有的情况,然后去网上看了下别人的代码,好厉害~是用迭代的想法,主要思路如下(摘抄):

1、考虑特殊情况即*s字符串或者*p字符串结束。

(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),否则无法匹配

(2)*s字符串未结束,而*p字符串结束,则无法匹配

2、*s字符串与*p字符串均未结束

(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,否则无法匹配。

(2)*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多(记为i)等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较,

只要匹配一种情况就算完全匹配

代码如下~
public boolean isMatch(String s, String p) {

if(s.length() == 0){
if(p.length() == 0 || (p.length()>1 && p.charAt(1) == '*' && isMatch(s,p.substring(2,p.length())))){
return true;
}else{
return false;
}
}else if(p.length() == 0){
return false;
}

if(p.length() == 1 || p.charAt(1) != '*'){
if(p.charAt(0) == '.' || p.charAt(0) == s.charAt(0)){
return isMatch(s.substring(1,s.length()),p.substring(1,p.length()));
} else{
return false;
}
}else{
if(p.charAt(0) !='.' && p.charAt(0) != s.charAt(0)){
return isMatch(s,p.substring(2,p.length()));
}
else{

if(isMatch(s.substring(0,s.length()),p.substring(2,p.length())))
return true;

int i = 0;
while(p.charAt(0) == '.' || p.charAt(0) == s.charAt(0+i)){
System.out.println(i);
if(isMatch(s.substring(i+1,s.length()),p.substring(2,p.length())))
return true;
if(i+1 == s.length())
break;
i++;
}
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: