题目描述:
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)该表达式位后面紧跟的不是'*',那么只需要比较该位表达式与所遍历到字串位是否相等即可('.'匹配所有字串位)。
(2)该表达式位后面紧跟的是'*',那么这就需要进行讨论,因为不知道这个表达式位究竟包含了字串中的多少位,那么就要讨论该表达式位包含了字串中符合条件的的0位,1位,2 位...各种情况,只要其中一种情况成功匹配,那么就代表字串与正则表达式匹配成功。
public class Regular_Expression_Matching {
public static boolean solve(char[] s,char[] p,int sIndex,int pIndex)
{
//s和p全部匹配则匹配成功
if(pIndex==p.length)
return sIndex==s.length;
if(pIndex==p.length-1||p[pIndex+1]!='*')
{
if(sIndex<s.length&&(s[sIndex]==p[pIndex]||p[pIndex]=='.'))
return solve(s,p,sIndex+1,pIndex+1);
else
return false;
}
else
{
while(sIndex<s.length&&(s[sIndex]==p[pIndex]||p[pIndex]=='.'))
{
if(solve(s,p,sIndex,pIndex+2))
return true;
else
sIndex++;
}
}
//假如某位表达式后面既是'*',但是该位又与所遍历到的字串位不匹配,那么就要跳过这个表达式(包括其后面的'*')。
return solve(s,p,sIndex,pIndex+2);
}
public static boolean isMatch(String s,String p)
{
return solve(s.toCharArray(),p.toCharArray(),0,0);
}
public static void main(String[] args) {
String s = "aab";
String p = ".*cd";
System.out.println(isMatch(s,p));
}
}