[Leetcode] Regular Expression Matching

Source: Internet
Author: User

Regular Expression Matching 

implement regular expression matching with support For ". '  and  ' * ' .

entire input string (not partial). The function prototype should be:bool IsMatch (const char *s, const char *p) Some examples:ismatch ("AA", "a") →falseismatch ( "AA", "AA") →trueismatch ("AAA", "AA") →falseismatch ("AA", "A *") →trueismatch ("AA", ". *") →trueismatch ("AB", ". *") →true IsMatch ("AaB", "C*a*b") →true

Problem Solving Ideas:

Test instructions to implement a regular expression match. which supports. and *

Divided into three different situations. The subscript for the current string and pattern is i,j, respectively.

1, if the current pattern is complete, that is, p[j]== ' ", if the end of the string, then return True, otherwise return false

2, if the next character of the pattern is not *, that is p[j+1]!= ' * '. Here is a discussion of the situation.

(1) If S[I]==P[J], recursive verification i+1, j+1

(2) if p[i]== '. ' and s[i]!= ' + ', recursive verification i+1, j+1

(3) Otherwise, return false

3, if the next character of the pattern is *, that is, p[j+1]== ' * ', then continuously through the recursive backtracking i+k,j+2 (k from 0 to Len (s)-i,j+2 means to cross the current character and *).

The code is as follows:

Class Solution {public:    bool IsMatch (string s, String p) {        return matchhelper (S, p, 0, 0);    }        BOOL Matchhelper (string& S, string& p, int i, int j) {        if (p[j]== ')            } {return s[i]== ';        }                if (p[j + 1]! = ' * ') {            return (s[i] = = P[j]) | | (P[j] = = '. ' && s[i]!= ') ") && Matchhelper (S, p, i + 1, j + 1);        }                while ((s[i] = = P[j]) | | (P[j] = = '. ' && s[i]!= ') ") {            if (Matchhelper (S, p, I, j+2)) return true;            i++;        }        Return Matchhelper (S, p, I, j+2);    }};


[Leetcode] Regular Expression Matching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.