leetcode Wildcard Matching
2014-08-29 15:24
232 查看
先把题目放上来
动态规划:
注意上面两个都是未能AC的。
'?' 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
自己用了两种方法做了这道题,无奈自己实力太差,两次都未能AC,第一次用到的是递归的思路,可是超时了,第二次选择了用动态规划的方法,同样未能AC,主要原因是空间超了,路漫漫其修远兮,吾将上下而求索,以此来勉(qi)励(pian)自己。
上代码:
bool isMatch(const char *s, const char *p) { if (*p == '\0') { return *s == '\0'; } if (*s == '\0') { return true; } if (*(p + 1) == '\0') { if (*p == '*') { return true; } else if (*p == '?') { return *(s + 1) == '\0'; } else { return *(s + 1) == '\0' && *p == *s; } } if (*p == '?') { return isMatch(s + 1, p + 1); } else if (*p == '*') { for (int i = 0; i < strlen(s); i++) { if (isMatch(s + i, p + 1)) { return true; } } return false; } else { if (*p != *s) { return false; } else { return isMatch(s + 1, p + 1); } } }
动态规划:
bool isMatch(const char *s, const char *p) { const int m = strlen(s); const int n = strlen(p); vector<vector<bool>> f(n + 1, vector<bool>(n + 1, false)); for (int i = 0; i <= n; i++) { f[i][0] = true; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (p[i - 1] == '?') { f[i][j] = f[i - 1][j - 1]; } else if (p[i - 1] == s[j - 1]) { f[i][j] = f[i - 1][j - 1]; } else if (p[i - 1] == '*') { if (i != 1) { int k; for (k = 1; k <= m; k++) { if (f[i - 1][k]) { break; } } for (int t = k; t <= m; t++) { f[i][t] = true; } break; } else { for (int k = 1; k <= m; k++) { f[1][k] = true; } } } else { return false; } } } return f [m]; }
注意上面两个都是未能AC的。
相关文章推荐
- (细节题)[LeetCode]Wildcard Matching
- LeetCode——Wildcard Matching
- Leetcode 之Wildcard Matching(32)
- LeetCode::Wildcard Matching
- Leetcode: Wildcard Matching
- LeetCode Wildcard Matching
- Wildcard Matching_Leetcode_#44
- [LeetCode] Wildcard Matching, Solution
- leetcode 44 Wildcard Matching
- leetcode Wildcard Matching greedy algrithm
- Leetcode题解---WildCard Matching Java实现
- 121_leetcode_Wildcard Matching
- Leetcode_Wildcard Matching
- 【leetcode】第44题 Wildcard Matching 题目+解析+代码
- leetcode:Wildcard Matching
- Wildcard Matching (Recursive and Non Recursive method) (Leetcode 网易有道面试题)
- Leetcode: Wildcard Matching
- [leetcode]Wildcard Matching @ Python
- leetcode Wildcard Matching
- ★leetcode44_Wildcard Matching