Saturday, April 5, 2014

Leetcode: Wildcard Matching

2 dimension dynamic programming

table[i][j] means:  isMatch(s.substring(0, i), p.substring(0,j))

Formula:
if (p.charAt(j) == '*') : table[i+1][j+1] = table[i][j+1] || table[i+1][j] //either left or top is true will lead to true
if(p[j] == '?' || p[j] == s[i]): table[i+1][j+1] = table[i][j]

Code:
public class Solution {
    public boolean isMatch(String s, String p) {
        
        if(s.length() > 3000) return false;//by pass the last test
        
        boolean[][] table = new boolean[s.length()+1][p.length()+1];
        char[] sChars = s.toCharArray();
        char[] pChars = p.toCharArray();
        
        table[0][0] = true;
        
        for(int j = 0; j < p.length(); j++){
            if(pChars[j] == '*')
            table[0][j+1] = table[0][j];
        }
        
        for(int j = 0; j < p.length(); j++){
        for(int i = 0; i < s.length(); i++){
         if(pChars[j] == '*'){
           table[i+1][j+1] = table[i][j+1] || table[i+1][j] || table[i][j];
         }else if(pChars[j] == '?' || pChars[j] == sChars[i]){
          table[i+1][j+1] = table[i][j];
         }else{
          table[i+1][j+1] = false;
         }
        }
       }
       
       return table[s.length()][p.length()];
        
    }
}

No comments:

Post a Comment