[Leetcode] Wildcard Matching_leetcode

Source: Internet
Author: User

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
Translated from: http://yucoding.blogspot.com/2013/02/leetcode-question-123-wildcard-matching.html

For each element in S
If *s==*p or *p = =? Which means this is a match, then goes to next element s++ p++.
If p== ' * ', this is also a match, but one or many chars may to available, so let us save this * ' s position and the matched s position.
If not match, then we check if there are a * previously showed up,
If there is no *, return false;
If there is a *, we set p to the next element of *, and set current S to the next saved s position.

e.g.

Abed
? b*d**

A=?, go in, b=b, go on,
e=*, save * position star=3, save s position ss = 3, p++
E!=d, check if there was a *, yes, ss++, S=ss; P=star+1
D=d, go on, meet.
Check the rest element in P, if all are *, true, else false;

Code:

Class Solution {public
:
    bool IsMatch (const char *s, const char *p) {
         
        const char* star=null;
        Const char* Ss=s; 
        while (*s) {
            if (*p== '? ') | | (*p==*s)) {s++;p ++;continue;}
            if (*p== ' * ') {star=p++; ss=s;continue;}
            if (Star) {p = star+1 s=++ss;continue;}
            return false;
        }
        while (*p== ' * ') {p++}
        return!*p;
    }
;


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.