LeetCode 43 Wildcard Matching
2014-11-24 18:46
344 查看
Implement wildcard pattern matching with support for
思路:使用DP,切记在DP之前需要剪枝。
由于木有以下代码,一直TLE,呜呜呜
'?'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
思路:使用DP,切记在DP之前需要剪枝。
由于木有以下代码,一直TLE,呜呜呜
int count = 0; for (int i = 0; i < p.length(); i++) { if (p.charAt(i) != '*') { count++; } } if (count > s.length()) { return false; }Accepted的代码如下
public class Solution {
public boolean isMatch(String s, String p) {
int count = 0; for (int i = 0; i < p.length(); i++) { if (p.charAt(i) != '*') { count++; } } if (count > s.length()) { return false; }
boolean[][] flag = new boolean[p.length() + 1][s.length() + 1];
flag[0][0] = true;
for (int i = 0; i < p.length(); i++) {
if (flag[i][0] && p.charAt(i) == '*')
flag[i + 1][0] = true;
for (int j = 0; j < s.length(); j++) {
if (p.charAt(i) == s.charAt(j) || p.charAt(i) == '?') {
flag[i + 1][j + 1] = flag[i][j];
}
if (p.charAt(i) == '*') {
flag[i + 1][j + 1] = flag[i + 1][j] || flag[i][j + 1];
}
}
}
return flag[p.length()][s.length()];
}
}
相关文章推荐
- LeetCode: Wildcard Matching
- LeetCode Online Judge 题目C# 练习 - Wildcard Matching
- 【leetcode】Wildcard Matching(hard) ★ 大神太牛了
- LeetCode: Wildcard Matching [043]
- [Leetcode] 44. Wildcard Matching
- [Leetcode] Wildcard Matching
- LeetCode 44. Wildcard Matching
- [LeetCode]Wildcard Matching
- [LeetCode] 44. Wildcard Matching 外卡匹配
- Leetcode 44. Wildcard Matching
- 121_leetcode_Wildcard Matching
- leetcode 10|44. Regular Expression Matching 44. Wildcard Matching
- leetcode 44 Wildcard Matching
- leetcode-44 Wildcard Matching 通配符匹配
- LeetCode题解-----Wildcard Matching
- LeetCode-- Wildcard Matching
- leetcode 44. Wildcard Matching
- 【LeetCode笔记】Wildcard Matching 和 Regular Expression Matching
- Leetcode:Wildcard Matching
- LeetCode 044 Wildcard Matching