Wildcard Matching

Problem:

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
   這道題的關鍵是認識到"*"的截斷效應,即:如果p[j]='*'且s[0...i]與p[0...j]匹配,那麼只需要判斷s[i+1...]與p[j...]是否匹配。所以,如果在p中出現多個'*',只需在下一個'*'出現之前,在s中找到與p中兩個'*'之間子串匹配的第一個子串。
Solution:
public class Solution {
    public boolean isMatch(String s, String p) {
     if(s==null&&p==null)
         return true;
     if(s==null||p==null)
         return false;
     int i = 0,j=0;
     int a = -1,b=0;
     while(i<s.length()&&j<=p.length())
     {
         if(j<p.length()&&p.charAt(j)=='*')
         {
             if(j==p.length()-1)
                 return true;
             a = i;
             b = ++j;
         }
         else if(j<p.length()&&(p.charAt(j)=='?'||s.charAt(i)==p.charAt(j)))
         {
             i++;
             j++;
        }
         else if(a>=0)
         {
             i = ++a;
             j = b;
         }
         else
         return false;
     }
     while(j<p.length()&&p.charAt(j)=='*')
         j++;
     if(i==s.length()&&j==p.length())
         return true;
     else 
         return false;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章