LC 44 Wildcard Matching(H)

Implement wildcard pattern matching with support for '?' and '*'

边界条件

解题思路

两个指针,当遇到'*'特殊处理,

public boolean isMatch(String s, String p) {
    int i = 0;
    int j = 0;
    int skipStart = -1;
    int iIndex = -1;
    // check s string one by one
    while (i<s.length()){
        // if s(i) == p(j) or p(j) = ?, both point move next
        if(j<p.length() && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?')){
            i++;
            j++;
        // if p(j) is '*', mark it and move p's Point to next.
        }else if(j<p.length() && p.charAt(j) == '*'){
            skipStart = j;
            iIndex = i;
            j++;
        // if have '*' happen, try to match s with p after '*' part.
        }else if(skipStart != -1){
            j = skipStart + 1;
            i = iIndex + 1;
            iIndex++;
        }else{
            return false;
        }
    }
    // p is longer than s, the rest p only can skip '*'
    while(j<p.length() && p.charAt(j) == '*'){
        j++;
    }
    return j == p.length();
}

Last updated

Was this helpful?