標籤:字元流 動態規劃 c++ 演算法 leetcode
題目
‘?’ 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
思路
此題和第十題 Regular Expression Matching極為相像,只不過這個題‘*’可代表任一字元串,而10題只能表示若干個前面字母。舉例來說,此題中*可以表示a,ab,abdfefa等,也可以表示空。但10題中*不可以單獨出現,其必須和它前面的字母共同構成一個運算式,比如說a*表示若干個a,也即a,aa,aaa,或空。
仍然採用DP,設定一個vectorre(n+1),存放第一個字串截止到該位置的匹配情況,然後從第二個字串開始遍曆,遇到*要特殊處理,對於字串2的每一位,都要從字串1中去尋找是否可以匹配上的位置,並把相應位置標記為真。每一個位置的狀態均由前一位置決定,也就是說前一位置不匹配,這一位置一定不能匹配。遍曆結束後輸出最後一個位置的匹配結果。
代碼
class Solution {public: bool isMatch(const char *s, const char *p) { int m = strlen(s); int n = strlen(p); if (n==0) return m==0; if (m>30000) return false; //沒有這句話有一個case:aaaaaa居多a的過不去。。。 vector<bool> re(m+1,false); re[0]=true; //預設第零位為匹配,因為有可能p[0]==* for (int i=0;i<n;i++){ if (p[i]==‘*‘){ //判斷是否為*,*需要特殊處理 for (int k=0;k<m;k++){ re[k+1]=re[k+1]||re[k]; //如果已經為真,則繼續為真;否則要取決於前一位。 } } else{ for (int j=m;j>0;j--){ //取決於前一位,並且要求這一位匹配 re[j]=re[j-1]&&(p[i]==s[j-1]||p[i]==‘?‘); } } re[0] = re[0]&&p[i]==‘*‘; //如果該位置不為*,則第零位不可為真 } return re[m]; }};
轉載請註明出處:http://blog.csdn.net/monkeyduck
歡迎留言,關注
【LeetCode】【C++】Wildcard Matching