1. 程式人生 > >[leetcode] 44. Wildcard Matching 解題報告

[leetcode] 44. Wildcard Matching 解題報告

題目連結: https://leetcode.com/problems/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

思路: 有兩種特殊字元, '?'代表匹配一個任意字元, 這個比較好處理. '*'匹配任意多個字元, 這個需要考慮匹配多個字元. 因此我們可以記下最後出現'*'的位置, 這樣當後面位置不匹配的時候再回到這裡將不匹配的字元用'*'來匹配. 這樣最後再判斷是否p指標停留的位置到最後都是*, 如果是的話則可以匹配, 否則不可以匹配. 一個例子如: s = "aa", p = "aa****".

程式碼如下:

class Solution {
public:
    bool isMatch(string s, string p) {
        int preS=-1, preP=-1, i=0, j=0, len1=s.size(), len2=p.size();
        while(i < len1)
        {
            if(s[i]==p[j] || p[j]=='?') i++, j++;
            else if(p[j]=='*') preS=i+1, preP = j++;
            else if(preP==-1) return false;
            else i = preS, j = preP;
        }
        while(p[j]=='*') j++;
        return i==len1&&j==len2;
    }
};
參考: https://leetcode.com/discuss/49254/fastest-non-dp-solution-with-o-1-space