標籤:style blog http color io ar 2014 cti
前天用遞迴LTE,昨天用動態規劃LTE,今天接著搞,改用貪進法。題目再放一次:
‘?‘匹配任一字元,‘*‘匹配任意長度字串
Some examples:isMatch("aa","a") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
The function prototype should be:bool isMatch(const char *s, const char *p)
思路其實更簡單,和遞迴的有點像,兩個字串從頭開始匹配,不匹配直接返回false,匹配,則兩個指標都加1,若p遇到*,則s++一直到匹配到p+1,當然要記錄此時p和s的位置,以便下次回溯.
還是用圖片說明吧:
用該方法,最差情況下複雜度為len_s*len_p,絕大情況下其實小很多.具體代碼如下:
class Solution {public: bool isMatch(const char *s, const char *p) { const char *last_s = NULL; const char *last_p = NULL; while (‘\0‘ != *s || ‘*‘ == *p) { if (*s == *p || ‘?‘ == *p) { s++; p++; continue; } if (‘*‘ == *p) { while (‘*‘ == *p) { last_p = p; p++; } while (‘\0‘ != *s && (*s != *p && ‘?‘ != *p)) { s++; } last_s = s; continue; } if (last_p != NULL) { p = last_p; s = last_s+1; continue; } return false; } if (‘\0‘ == *p) { return true; } return false; }};
這次終於AC了.
最初的時候直觀的感覺如果p中有n個*就要儲存多個n個位置以回溯,其實不用,只要保證前面的子串匹配了,後面的*匹配不受影響,就是有多種匹配方案,但是只要找到一種就可以了.
這個解決方案感覺不是很美,一是思路不清爽,很容易忽略一些特殊情況,Wrong Answer了兩次才成功;二是不像前兩種,能解決s和p都帶有萬用字元的情況,只能做只有p中有萬用字元,s中也有的情況感覺分析起來很複雜,不直觀.