日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】44. Wildcard Matching (2 solutions)

發布時間:2023/12/10 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】44. Wildcard Matching (2 solutions) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Wildcard Matching

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

?

解法一:

這題想法參考了https://oj.leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution,

類似于一種有限狀態機的做法。

主要思想如下:

由于*匹配多少個字符是不一定的,于是首先假設*不匹配任何字符。

當后續匹配過程中出錯,采用回溯的方法,假設*匹配0個字符、1個字符、2個字符……i個字符,然后繼續匹配。

因此s需要有一個spos指針,記錄當p中的*匹配i個字符后,s的重新開始位置。

p也需要一個starpos指針指向*的位置,當回溯過后重新開始時,從starpos的下一位開始。

class Solution { public:bool isMatch(const char *s, const char *p) {char* starpos = NULL;char* spos = NULL;while(true){if(*s == 0 && *p == 0)//match allreturn true;else if(*s == 0 && *p != 0){//successive *p must be all '*'while(*p != 0){if(*p != '*')return false;p ++;}return true;}else if(*s != 0 && *p == 0){if(starpos != NULL){//maybe '*' matches too few chars in sp = starpos + 1;s = spos + 1;spos ++; //let '*' matches one more chars in s }else//*s is too longreturn false;}else{if(*p == '?' || *s == *p){s ++;p ++;}else if(*p == '*'){starpos = (char*)p;spos = (char*)s;p ++; //start successive matching from "'*' matches non" }//currently not matchelse if(starpos != NULL){//maybe '*' matches too few chars in sp = starpos + 1;s = spos + 1;spos ++; //let '*' matches one more chars in s }else//not matchreturn false;}}} };

?

解法二:

模仿Regular Expression Matching的遞歸做法,小數據集上能過。

當*數目太多時會超時。

class Solution { public:bool isMatch(const char *s, const char *p) {if(*p == 0)return (*s == 0);if(*p == '*'){//case1: *p matches 0 chars in sif(isMatch(s, p+1))return true;//case2: try all possible numberswhile(*s != 0){s ++;if(isMatch(s, p+1))return true;}return false;}else{if((*s==*p) || (*p=='?'))return isMatch(s+1, p+1);elsereturn false;}} };

以下是我的測試代碼,小數據上全部通過:

int main() {Solution s;cout << s.isMatch("aa","a") << endl;cout << s.isMatch("aa","aa") << endl;cout << s.isMatch("aaa","aa") << endl;cout << s.isMatch("aa","*") << endl;cout << s.isMatch("aa","a*") << endl;cout << s.isMatch("ab","?*") << endl;cout << s.isMatch("aab","c*a*b") << endl;return 0; }

?

轉載于:https://www.cnblogs.com/ganganloveu/p/4161767.html

總結

以上是生活随笔為你收集整理的【LeetCode】44. Wildcard Matching (2 solutions)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。