[LeetCode] Regular Expression Matching

Source: Internet
Author: User

[LeetCode] Regular Expression Matching

 

Regular Expression Matching

 

Implement regular expression matching with support'.'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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

Solution:

The question is to implement regular expression matching. Supported. And *

There are three cases. Set the subscript of the current string and mode to I, j, respectively.

1. If the current mode is matched, p [j] = '\ 0'. If the string ends, true is returned; otherwise, false is returned.

2. If the next character in the mode is not *, p [j + 1]! = '*'. We will discuss the situation here.

(1) If s [I] = p [j], recursive verification of I + 1, j + 1

(2) If p [I] = '.' And s [I]! = '\ 0', recursive verification I + 1, j + 1

(3) Otherwise, false is returned.

3. If the next character of the mode is *, that is, p [j + 1] = '*', Recursive Backtracking is performed continuously, j + 2 (k increases from 0 to len (s)-I, j + 2 means crossing 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]=='\0'){            return s[i]=='\0';        }                if( p[j + 1] != '*'){            return ((s[i] == p[j]) || (p[j] == '.' && s[i]!='\0')) && matchHelper(s, p, i + 1, j + 1);        }                while((s[i] == p[j]) || (p[j] == '.' && s[i]!='\0')){            if(matchHelper(s, p, i, j+2)) return true;            i++;        }        return matchHelper(s, p, i, j+2);    }};


 

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.