标签:
‘?‘ 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
1. 动态规划
bool isMatch(string s, string p) { int ls = s.length(), lp = p.length(), i, j; vector<vector<bool>> dp(2, vector<bool>(lp+1, 0)); bool k = 1; dp[0][0] = 1; for(i = 1; i <= lp; i++) dp[0][i] = dp[0][i-1] && ‘*‘ == p[i-1]; for(i = 1; i <= ls; i++) { dp[k][0] = 0; for(j = 1; j <= lp; j++) { if(‘*‘ == p[j-1]) dp[k][j] = dp[k][j-1] || dp[!k][j]; else dp[k][j] = dp[!k][j-1] && (p[j-1] == s[i-1] || ‘?‘ == p[j-1]); } k = !k; } return dp[!k][lp]; }
2. 不匹配的时候回到上一个星号的地方,使星号多匹配一个字符。
bool isMatch(string s, string p) { int ls = s.length(), lp = p.length(), last_i = -1, last_j = -1, i = 0, j = 0; while(s[i]) { if(‘*‘ == p[j]) { j++; if(!p[j]) return 1; last_i = i; last_j = j; } else if(s[i] == p[j] || ‘?‘ == p[j]) { i++; j++; } else if(last_i != -1) { i = ++last_i; j = last_j; } else return 0; } while(‘*‘ == p[j]) j++; return !p[j]; }
标签:
原文地址:http://www.cnblogs.com/argenbarbie/p/5248076.html