题目
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的下一字符是不是'*'分两种情况处理:
1. p的下个字符是'*',如果p和s当前字符相同或p当前字符是'.',则一直往右移动直到p没有'.*'或'x*'这样的情况,递归判断(x是指跟s相同的字符)
2. p的下个字符不是'*',如果p和s当前字符相同或p当前字符是'.',则p和s往右移动一个字符,递归判断
注意由于Python递归效率较差,因此用Python要尽量减小算法复杂度
代码
Python
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
sLen = len(s)
pLen = len(p)
if (pLen == 0):
return sLen == 0
if (pLen == 1):
if (p == s) or ((p == '.') and (len(s) == 1)):
return True
else:
return False
#p的最后一个字符不是'*'也不是'.'且不出现在s里,p跟s肯定不匹配
if (p[-1] != '*') and (p[-1] != '.') and (p[-1] not in s):
return False
if (p[1] != '*'):
if (len(s) > 0) and ((p[0]==s[0]) or (p[0]=='.')):
return self.isMatch(s[1:],p[1:])
return False
else:
while (len(s) > 0) and ((p[0]==s[0]) or (p[0]=='.')):
if (self.isMatch(s,p[2:])):
return True
s = s[1:]
return self.isMatch(s,p[2:])
Java
public class Solution {
public boolean isMatch(String s, String p){
int sLen = s.length();
int pLen = p.length();
if(pLen == 0) return sLen == 0;
if(pLen == 1){
if(p.equals(s) || p.equals(".") && s.length() == 1) return true;
else return false;
}
if(p.charAt(pLen-1) != '*' && p.charAt(pLen-1) != '.' && !s.contains(p.substring(pLen-1))) return false;
if(p.charAt(1) == '*'){
//p的下个字符是'*',如果p和s当前字符相同或p当前字符是'.',则一直往右移动
while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.' )){
if(isMatch(s,p.substring(2))) return true;
s = s.substring(1);
}
return isMatch(s,p.substring(2));
}
else{
//p的下个字符不是'*',如果p和s当前字符相同或p当前字符是'.',则p和s往右移动一个字符
if(s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){
return isMatch(s.substring(1),p.substring(1));
}
return false;
}
}
}