Wildcard Matching
阿新 • • 發佈:2017-12-22
problem || problems spa 下午 研究 bool set str
https://leetcode.com/problems/wildcard-matching/description/
狀態轉移方程考慮s[i]恰與p[j]匹配的兩種情況:相等或‘?‘,以及p[j]為‘*‘的兩種情況:s[i]為與‘*‘匹配的串的子串或‘*‘匹配一個空串即可。
主要功夫花在處理邊界上。
邊界處理格式:(?)*?*。
下午研究一下優化。
bool isMatch(string s, string p) { int s_length = s.size(); int p_length = p.size(); if (s_length == 0 && p_length == 0) return true; else if (s_length != 0 && p_length == 0) return false; else if (s_length == 0 && p_length != 0){ int flag = 0; for (int i = 0; i < p_length; i++) if (p[i] != ‘*‘) flag = 1; return flag? false: true; } int status[s_length][p_length]; memset(status, 0, (s_length)*sizeof(status[0])); status[0][0] = s[0] == p[0] || p[0] == ‘?‘ || p[0] == ‘*‘; if (status[0][0]){ int flag = 0; while (++flag < p_length && p[flag] == ‘*‘) status[0][flag] = 1; if (flag < p_length && p[0] == ‘*‘ && (s[0] == p[flag] || p[flag] == ‘?‘)){ status[0][flag] = 1; while (++flag < p_length && p[flag] == ‘*‘) status[0][flag] = 1; } } for (int i = 1; i < s_length; i++){ status[i][0] = p[0] == ‘*‘? 1: 0; for (int j = 1 ; j < p_length; j++) status[i][j] = (s[i] == p[j] || p[j] == ‘?‘)? status[i - 1][j - 1]: p[j] == ‘*‘? status[i][j - 1] || status[i - 1][j]: 0; } return status[s_length - 1][p_length - 1]; }
Wildcard Matching