首页 > 代码库 > Wildcard Matching leetcode java

Wildcard Matching leetcode java

题目

 

Implement wildcard pattern matching with support for ‘?‘ 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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false

题解
本文代码引用自:http://blog.csdn.net/perfect8886/article/details/22689147
 1     public boolean isMatch(String s, String p) {  
 2         int i = 0;  
 3         int j = 0;  
 4         int star = -1;  
 5         int mark = -1;  
 6         while (i < s.length()) {  
 7             if (j < p.length()  
 8                     && (p.charAt(j) == ‘?‘ || p.charAt(j) == s.charAt(i))) {  
 9                 ++i;  
10                 ++j;  
11             } else if (j < p.length() && p.charAt(j) == ‘*‘) {  
12                 star = j++;  
13                 mark = i;  
14             } else if (star != -1) {  
15                 j = star + 1;  
16                 i = ++mark;  
17             } else {  
18                 return false;  
19             }  
20         }  
21         while (j < p.length() && p.charAt(j) == ‘*‘) {  
22             ++j;  
23         }  
24         return j == p.length();  
25     }