您的位置:首页 > 其它

LeetCode OJ算法题(十):Regular Expression Matching

2014-07-15 14:06 211 查看
题目:

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

解法:

本题旨在判断两个字符串是否完全一样,关键在于*号的支持,*号表示前面的字符重复0次或者更多次,因此需要对每个字符后面是否为*号加以区分,若为*号,则该符号可能重复0次~

下面分情况讨论(当前指针处于si,pi):

1、若pi+1不为*,则直接比较si和pi对应的字符是否相等,如果不等直接false,如果相等,则继续比较si+1和pi+1状态;

2、若pi+1为*,那么我们可以把s字符串记作{Xi},p字符串记作{Z*Yj},那么我们需要依次比较{Xi}vs{Yj},{Xi}vsZ{Yj},{Xi}vsZZ{Yj}。。。。。。等,其中,当我们比较{Xi}与Z...Z(n个Z){Yj}时,必有{Xi}的前n个字符都是Z,循环终止的条件就是n大于{Xi}中前缀Z的个数。

public class No10_RegularExpressionMatching {
public static void main(String[] args){
System.out.println(isMatch("ca", "c*a"));
}
public static boolean isMatch(String s, String p) {
if(p.length() == 0) return s.length() == 0;
if(p.length() == 1) return s.length() == 1 && (s.equals(p) || p.charAt(0) == '.');
int si = 0, pi = 0;
if(p.charAt(pi+1) != '*'){
if(si<s.length() && (s.charAt(si) == p.charAt(pi) || p.charAt(pi) == '.')){
return isMatch(s.substring(si+1), p.substring(pi+1));
}
return false;
}
else{
while(si<s.length() && (s.charAt(si) == p.charAt(pi) || p.charAt(pi) == '.')){
if(isMatch(s.substring(si), p.substring(pi+2)))
return true;
si++;
}
return isMatch(s.substring(si), p.substring(pi+2));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode