您的位置:首页 > 其它

【正则表达式判断】Regular Expression Matching

2014-04-06 16:37 381 查看
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

参考:http://blog.csdn.net/fightforyourdream/article/details/17717873
public class Solution {

public boolean isMatch(String s, String p, int sp, int pp){
int ls = s.length();
int lp = p.length();

if(pp >= lp) return sp>=ls;

if(pp == lp-1) return (sp==ls-1) && (s.charAt(sp)==p.charAt(pp) || p.charAt(pp)=='.');

if(pp+1 < lp && p.charAt(pp + 1) != '*'){//如果下一个字符不为*,则比较s和p当前的字符
if((sp!=ls) && (s.charAt(sp)==p.charAt(pp) || p.charAt(pp)=='.'))
return isMatch(s, p, sp+1, pp+1);
else return false;
}
else{//若下一个字符为*
while((sp<ls) && (s.charAt(sp)==p.charAt(pp) || p.charAt(pp)=='.')){
if(isMatch(s, p, sp, pp+2)) return true;//如果把当前s中字符放入后续匹配成功,即p的下一*没有用
sp++;//不成功则将*执行一次
}
return isMatch(s, p, sp, pp+2);
}
}

public boolean isMatch(String s, String p) {
return isMatch(s, p, 0, 0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: