# LeetCode(10)RegularExpresssionMatching

2863人阅读 评论(0)

'.' 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

isMatch("ab", ".*") → true

//
//  Solution.h
//  LeetCodeOJ_010_RegMatching
//
//  Created by feliciafay on 12/4/13.
//

#ifndef LeetCodeOJ_010_RegMatching_Solution_h
#define LeetCodeOJ_010_RegMatching_Solution_h
#include <iostream>
#include <string>
#include <assert.h>
// Input:	"bbbba", ".*a*a"
class Solution {
public:
bool isMatch(const char *s, const char *p) {
assert(s && p);
if (*p == '\0') return *s == '\0';

// next char is not '*': must match current character
if (*(p+1) != '*') {
assert(*p != '*');
return ((*p == *s) || (*p == '.' && *s != '\0')) && isMatch(s+1, p+1);
}
// next char is '*'
while ((*p == *s) || (*p == '.' && *s != '\0')) {
if (isMatch(s, p+2))
return true;
s++;
}
//继续匹配剩下的部分
return isMatch(s, p+2);
}
};
#endif

(1)欣赏一下这句的简洁和巧妙
return ((*p == *s) || (*p == '.' && *s != '\0')) && isMatch(s+1, p+1);
(2)

    if (isMatch(s, p+2)) return true;

    return  (isMatch(s, p+2));

(3)

//错误写法
s++;
if (isMatch(s, p+2)) return true;

if (isMatch(s, p+2)) return true;
s++;

if (isMatch(s, p+2)) return true;
s++;
(4) LeetCode对思路讲解的的原话

We need some kind of backtracking mechanism such that when a matching fails, we return to the last successful matching state and attempt to match more characters in s with ‘*’. This approach leads naturally to recursion.

If the next character of p is NOT ‘*’, then it must match the current character of s. Continue pattern matching with the next character of both s and p.
If the next character of p is ‘*’, then we do a brute force exhaustive matching of 0, 1, or more repeats of current character of p… Until we could not match any more characters.

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1206660次
• 积分：13441
• 等级：
• 排名：第995名
• 原创：408篇
• 转载：14篇
• 译文：0篇
• 评论：139条
博客专栏
 LeetCode(C++) 文章：47篇 阅读：101773
阅读排行
最新评论