LeetCode: Wildcard Matching

这题第一次做用dfs,结果过不了large,网上寻找到答案,这里s和p指针是会变的,重点处理ptr遇到*的时候,这个时候s和p都往后挪,p重新定位,看s后面和p后面的是不是match,如果不match则s向后移,再继续看后面的是不是match,直到s到底为止,这里str和ptr是浮动指针,s和p相对静止,记录前一个邵点。

 1 class Solution {

 2 public:

 3     bool isMatch(const char *s, const char *p) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         bool star = false;

 7         const char *str, *ptr;

 8         for (str = s, ptr = p; *str != '\0'; str++, ptr++) {

 9             if (*ptr == '*') {

10                 star = true;

11                 s = str, p = ptr;

12                 while (*p == '*') p++;

13                 if (*p == '\0') return true;

14                 str = s-1, ptr = p-1;

15             }

16             else if (*ptr == '?') continue;

17             else {

18                 if (*str != *ptr) {

19                     if (!star) return false;

20                     s++;

21                     str = s-1, ptr = p-1;

22                 }

23             }

24         }

25         while (*ptr == '*') ptr++;

26         return *ptr == '\0';

27     }

28 };

 while的可能更好懂

 1 class Solution {

 2 public:

 3     bool isMatch(const char *s, const char *p) {

 4         const char *s1, *p1;

 5         s1 = s, p1 = p;

 6         bool star = false;

 7         while (*s1 != '\0') {

 8             if (*s1 == *p1 || *p1 == '?') {

 9                 s1++, p1++;

10             }

11             else {

12                 if (*p1 == '*') {

13                     star = true;

14                     p = p1, s = s1;

15                     while (*p == '*') p++;

16                     if (*p == '\0') return true;

17                     p1 = p;

18                 }

19                 else {

20                     if (!star) return false;

21                     s++;

22                     s1 = s, p1 = p;

23                 }

24             }

25         }

26         while (*p1 == '*') p1++;

27         return *p1 == '\0';

28     }

29 };

 

你可能感兴趣的:(LeetCode)