LeetCode 44 - Wildcard Matching

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

Solution:

public boolean isMatch(String s, String p) {
    int i=0, j=0, m=s.length(), n=p.length();
    int star = -1, match = -1;
    while(i < m) {
        if(j<n && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?')) {
            i++;
            j++;
        } else if(j<n && p.charAt(j) == '*') {
            match = i;
            star = j++;
        } else if(star != -1) {
            i = ++match;
            j = star + 1;
        } else {
            return false;
        }
    }
    for(; j<n; j++) {
        if(p.charAt(j) != '*') return false;
    }
    return true;
}

 

你可能感兴趣的:(LeetCode 44 - Wildcard Matching)