44 Wildcard Matching

44 Wildcard Matching


https://www.youtube.com/watch?v=3ZDZ-N0EPV0&t=423s


intialization: 
Empty string and empty pattern : true 
Empty string and “*” = true
Others false , since the initialized default value for the Boolean 2d array are false, so we 
Only need to change the true part 

Same as after two cases, else, we should return false, 
And since the default initialized value are false, and 
If the two cases didn’t turn it into true, and it should be 
Default value as false






Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5






class Solution {
    public boolean isMatch(String s, String p) {
     
      
      
      // replace multiple * with one * 
      // e.g. a**b***c --> a*b*c
      boolean met = false;
      StringBuilder sb = new StringBuilder();
      for(int i = 0; i < p.length(); i++){
        if(p.charAt(i) != '*'){
          sb.append(p.charAt(i));
          met = false;
        }
        if(p.charAt(i) == '*' && met == false){
          sb.append('*');
          met = true;
        }else{
          continue;
        }
      }
      
      
      char[] str = s.toCharArray();
      char[] pattern = sb.toString().toCharArray();
      
      
      boolean T[][] = new boolean[str.length + 1][pattern.length + 1];
      
      if(pattern.length > 0 && pattern[0] == '*'){
        T[0][1] = true;
      }
      
      T[0][0] = true;
      
      for(int i = 1; i < T.length; i++){
        for(int j = 1; j < T[0].length; j++){
          // why it's j-1, because the pattern starts from 0 index
          if(pattern[j-1] == str[i-1] || pattern[j-1] == '?'){
            T[i][j] = T[i-1][j-1];
          }else if (pattern[j-1] == '*'){
            T[i][j] = T[i-1][j] || T[j-1][i];
          }
        }
      }
      return T[str.length][pattern.length];
    }
}

 

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false

posted on 2018-08-10 14:51  猪猪&#128055;  阅读(88)  评论(0)    收藏  举报

导航