[leetcode]Wildcard Matching


一看,直接遞歸...果然超時了TAT

不過我覺得能把遞歸寫對就不錯啦,應該滿足面試要求了吧.

不過TLE我也不知道我寫對沒有.

 

正確的做法是貪心.

大概是這樣的

我們來匹配s和p

如果匹配就s++ , p++

如果不匹配的話就看p之前知否有*

當然是否有*我們需要記錄的,遇到*就記錄當前*的位置和匹配到的s的位置

然后從*的下一位置匹配,開始匹配0個字符

如果ok往后走,往后不ok,那么匹配1個字符...同理2,3,4個字符(有點回溯的感覺吧

所以實踐復雜度是O(len(s) * len(p))

 

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        //? match one
        //* match 0,1,2,3..
        // aaaabc *c true
        const char* star = nullptr;
        const char* rs = nullptr;
        
        while(*s) {
            if(*s == *p || *p == '?') { //match
                s++; p++;
                continue;
            }
            if(*p == '*') { 
                star = p; // record star
                p++; //match from next p
                rs = s; // record the position of s , star match 0
                continue;
            } 
            if(star != nullptr) { //if have star in front then backtrace
                p = star + 1; //reset the position of p 
                s = rs + 1; 
                rs ++; //star match 1,2,3,4,5....
                continue;
            }
            return false; //if not match return false
        }
        while(*p == '*') p++; //skip continue star
        return *p == '\0'; // successful match
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM