41. Regular Expression Matching

2017-03-20  本文已影响20人  时光杂货店

题目

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

频度: 3

解题之法

class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        if (p.size() == 1) {
            return (s.size() == 1 && (s[0] == p[0] || p[0] == '.'));
        }
        if (p[1] != '*') {
            if (s.empty()) return false;
            return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1)); //从下标1一直到结尾
        }
        while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {
            if (isMatch(s, p.substr(2))) return true;
            s = s.substr(1);
        }
        return isMatch(s, p.substr(2));
    }
};

分析

这道求正则表达式匹配的题和那道 Wildcard Matching 通配符匹配的题很类似。
不同点在于的意义不同:Wildcard Matching中,表示可以代替任意个数的字符,而这道题中的表示之前那个字符可以有0个,1个或是多个,就是说,字符串ab,可以表示b或是aaab,即a的个数任意,这道题的难度要相对之前那一道大一些,分的情况的要复杂一些,需要用递归Recursion来解,大概思路如下:

上一篇 下一篇

猜你喜欢

热点阅读