1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Wildcard Matching

Posted on 2014-01-13 11:09  1957  阅读(5279)  评论(2编辑  收藏  举报

一看,直接递归...果然超时了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
    }
};