LeetCode : Wildcard Matching
2012-12-09 04:56
399 查看
Implement wildcard pattern matching with support for
回头得自己写一个了
下面是一个JAVA实现,递归的方法做的,挺简洁。
'?'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
回头得自己写一个了
class Solution { public: bool isMatch(const char *s, const char *p) { // Start typing your C/C++ solution below // DO NOT write int main() function const char *str, *pat; bool star = false; for (str = s, pat = p; *str != '\0'; ++str, ++pat) { switch(*pat) { // 遇到'?',那么不管*str是任何字母都能匹配 case '?': break; case '*': star = true; // 暂时忽略‘*’ s = str; p = pat; do { ++p; }while(*p == '*'); // 如果'*'之后,pat是空的,直接返回true if (!*p) return true; // 重新开始匹配 str = s - 1; pat = p - 1; break; default: if (*str != *pat) { // 如果前面没有'*',则匹配不成功 if (!star) return false; // 从s的下一位和'*'之后的p重新开始匹配 ++s; str = s - 1; pat = p - 1; } break; } } while (*pat == '*') ++pat; return (!*pat); } };
下面是一个JAVA实现,递归的方法做的,挺简洁。
public class Solution { public boolean isMatch(String s, String p) { // Start typing your Java solution below // DO NOT write main() function assert(p!=null && (p.length()==0 || p.charAt(0)!='*')); if(p.length()==0) return s.length()==0; if(p.length()==1 || p.charAt(1)!='*'){ if(s.length()<1 || (p.charAt(0)!='.' && p.charAt(0)!=s.charAt(0))) return false; return isMatch(s.substring(1),p.substring(1)); }else{ int i=-1; while(i<s.length() && (i<0 || p.charAt(0)=='.' || p.charAt(0)==s.charAt(i))){ if(isMatch(s.substring(i+1),p.substring(2))) return true; i++; } return false; } } }
相关文章推荐
- Leetcode-Wildcard Matching
- Leetcode:44. Wildcard Matching
- 【LeetCode】44. Wildcard Matching (2 solutions)
- Leetcode 44. Wildcard Matching
- [LeetCode] Wildcard Matching
- Leetcode 44. Wildcard Matching (Hard) (cpp)
- LeetCode-Wildcard Matching
- [LeetCode]Wildcard Matching 通配符匹配(贪心)
- Leetcode Wildcard Matching
- leetcode 44. Wildcard Matching
- leetcode -- Wildcard Matching --再看
- LeetCode "Wildcard Matching"
- leetcode 95: Wildcard Matching (uncompleted.)
- Wildcard Matching -- leetcode
- 【leetcode】Wildcard Matching
- LeetCode 43 Wildcard Matching
- leetcode:Wildcard Matching
- LeetCode题解-----Wildcard Matching
- [LeetCode] Wildcard Matching 通配符匹配
- Leetcode 44. Wildcard Matching