您的位置:首页 > 编程语言 > Java开发

[Leetcode] Regular Expression Matching (Java)

2013-12-27 09:40 351 查看
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


正则匹配,p为正则表达式,s为要匹配字符串,‘.’代表任意字符,‘a*’代表能出现0次或多次a,要返回是否能整体匹配而不是部分匹配。

1)p 0位要考虑的情况有点儿多

2)p 1位

3)p的第二位不为‘*’,则s位数要大于1,s第一位==p第一位或p第一位为‘.’,之后继续比较后面

4)p第二位为‘*’,则考虑几种情况:

a)s= abbbbbc ,p= ab*c

b)s=abcabcab ,p= a.*c.*b等

都要迭代比较
public class RegularExpressionMatching {
public boolean isMatch(String s, String p) {
if(p.length()==0)
return s.length()==0;
if(p.length()==1)
return s.length()==1&&(p.charAt(0)==s.charAt(0)||(p.charAt(0)=='.'&&s.length()!=0));
else if(p.charAt(1)!='*')
return (s.length()>0)&&(s.charAt(0)==p.charAt(0)||(p.charAt(0)=='.'&&s.length()!=0))&&isMatch(s.substring(1), p.substring(1));
int sIndex = 0;
int pIndex = 0;
while (sIndex<s.length()&&pIndex<p.length()&&(s.charAt(sIndex)==p.charAt(pIndex)||(p.charAt(pIndex)=='.'&&s.length()!=0))) {
if(isMatch(s.substring(sIndex), p.substring(pIndex+2)))
return true;
sIndex++;
}
return isMatch(s.substring(sIndex), p.substring(pIndex+2));
}
public static void main(String[] args) {
String s = "ab";
String p = ".bab";
System.out.println(new RegularExpressionMatching().isMatch(s, p));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: