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 class Solution {
    public boolean isMatch(String s, String p) {
        boolean dp[][] = new boolean[p.length() + 1][s.length() + 1];

        for(int i = 0; i <= p.length(); i++) {
            for(int j = 0; j <= s.length(); j++) {
                if(i == 0) {
                    dp[i][j] = j == 0;
                } else if(j == 0) {
                    if(p.charAt(i-1) == '*' && dp[i-1][j]) dp[i][j] = true;
                } else {
                    if( ((p.charAt(i-1) == s.charAt(j-1)) || p.charAt(i-1) == '?') && dp[i-1][j-1]) dp[i][j] = true;
                    else if(p.charAt(i-1) == '*' && (dp[i-1][j-1] || dp[i][j-1] || dp[i-1][j])) dp[i][j] = true;
                }

            }

        }

        return dp[p.length()][s.length()];
    }
}

results matching ""

    No results matching ""