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:

  1. dp[i][j] represent string s from [0,i] matches with string p from [0,j]
  2. initialization:
    1. dp[0][0] = true
    2. dp[i][0] = false
    3. dp[0][j] only = true when all the character starting from position 0 = '*'
  3. update
    1. if s.char = p.char || p.char == '?'
      1. dp[i][j] = dp[i-1][j-1]
    2. if p.char = '*'
      1. dp[i][j] = dp[i-1][j] || dp[i][j-1] ----> *represent n or 0 elements
    3. otherwise
      1. false
public boolean isMatch(String s, String p) {
        boolean[][] dp = boolean[s.length()+1][p.length()+1];
        dp[0][0] = true;
        for(int i = 1; i <= p.length(); i++){
            if(p.charAt(i-1) =='*'){
                dp[0][i] = dp[0][j-1];
            }
        }

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

results matching ""

    No results matching ""