Wildcard Matching

Source

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

Java

public class Solution {
    public boolean isMatch(String str, String pattern) {
        int s = 0, p = 0, preS = -1, preP = -1;            
        while (s < str.length()){
            // advancing both pointers
            if (p < pattern.length()  && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))){
                s++;
                p++;
            }
            // * found, only advancing pattern pointer
            else if (p < pattern.length() && pattern.charAt(p) == '*'){
                preP = p;
                preS = s;
                p++;
            }
            // last pattern pointer was *, advancing string pointer
            else if (preP != -1){
                p = preP + 1;
                preS++;
                s = preS;
            }
            //current pattern pointer is not star, last patter pointer was not *
            //characters do not match
            else return false;
        }

        //check for remaining characters in pattern
        while (p < pattern.length()){
            if(pattern.charAt(p)!='*'){
                return false;
            }
            p++;
        }
        return true;        
    }
}

Reference

linear runtime and constant space solution

Wildcard Matching