Wildcard Matching leetcode java

愛做飯的小瑩子發表於2014-08-06

題目

 

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") → 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

題解
本文程式碼引用自: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     }
 

相關文章