您的位置:首页 > 编程语言 > C语言/C++

Leetcode_wildcard-matching(c++ and python version)

2014-04-10 22:17 477 查看
地址:http://oj.leetcode.com/problems/wildcard-matching/

Implement wildcard pattern matching with support for
'?'
and
'*'
.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

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", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

思路:(1)如果*s与*p相等或者*p=='?', s++, p++, 继续下一次判断;
(2)若*p=='*', 先用copyp和copys分别把p和s存一份(其实存的是起始位置,可以做*匹配的起始位置), s的位置不变,++p (这里其实是*不匹配任何,若之后不匹配,再退回来匹配)
(3)若copyp不为空,即之前存在*,现在可以匹配,p = copyp + 1, 即从*之后开始, s = ++copys, s也是从当初copys开始,不过copys本身也要自增(记录*已匹配字符数),每自增一次,代表p中的*匹配多一个字符,每次如此p = copyp + 1, 从*后开始匹配,不匹配的话再重复(即*再多匹配s中的一个字符), 直到s为空.
(4)前三都不符合,无法匹配。
可参考:http://blog.csdn.net/doc_sgl/article/details/12721187

c++参考代码:
class Solution {
public:
bool isMatch(const char *s, const char *p) {
const char *copyp = NULL, *copys = s;
while(*s)
{
if(*s==*p || *p=='?')
{
++s;
++p;
}
else if(*p=='*')
{
copyp = p++;
copys = s;
}
else if(copyp)
{
p = copyp+1;
s = ++copys;
}
else
return false;
}
while(*p && *p=='*')
++p;
return !(*p);
}
};


python 参考代码:
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
p += '\0'
copys = copyp = ""
flag = True
while s:
if s[0] == p[0] or p[0] == '?':
s = s[1:]
p = p[1:]
elif p[0] == '*':
copyp = p
copys = s
p = p[1:]
elif copyp:
copys = copys[1:]
s = copys
p = copyp[1:]
else:
return False

while p and p[0]=='*':
p = p[1:]
return p[0]=='\0'


python的代码真是折腾死了,没有指针真是不方便啊!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: