Sunday, July 26, 2015

Regular Expression Matching

Regular Expression Matching

25%
Accepted
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)
Have you met this question in a real interview? 
Yes
Example
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
public class Solution {
    /**
     * @param s: A string 
     * @param p: A string includes "." and "*"
     * @return: A boolean
     */
    public boolean isMatch(String s, String p) {
        // write your code here
        if(p.length() == 0){
            return s.length() == 1;
        }
        
        if(p.length() == 1){
            return s.length() == 1 && (p.charAt(0) == '.' || p.charAt(0) == s.charAt(0));
        }
        
        if(p.charAt(1) == '*'){
            if(isMatch(s, p.substring(2))) return true;
            return s.length() > 0 && (p.charAt(0) == '.' || p.charAt(0) == s.charAt(0)) && isMatch(s.substring(1), p);
           
        } else {
            return s.length() > 0 && (p.charAt(0) == '.' || p.charAt(0) == s.charAt(0)) && isMatch(s.substring(1), p.substring(1));
        }
    }
}


public class Solution {
    /**
     * @param s: A string 
     * @param p: A string includes "." and "*"
     * @return: A boolean
     */
    public boolean isMatch(String s, String p) {
        // write your code here
       boolean[][] dp = new boolean[s.length()+1][p.length()+1];
       dp[0][0] = true;
       for(int i = 1; i <= p.length(); i++){
           dp[0][i] = i > 1 && p.charAt(i-1) == '*' && dp[0][i-2];
       }
       
       for(int i = 0; i < s.length(); i++){
           for(int j = 0; j < p.length(); j++){
               if(p.charAt(j) != '*'){
                   dp[i+1][j+1] = (p.charAt(j) == '.' || p.charAt(j) == s.charAt(i)) && dp[i][j];
               } else {
                   dp[i+1][j+1] = j > 0 && dp[i+1][j-1] || dp[i+1][j] ||
                   (j > 0 && (p.charAt(j-1) == '.' || s.charAt(i) == p.charAt(j-1)) && dp[i][j+1]);
               }
           }
       }
       return dp[s.length()][p.length()];
    }
}

No comments:

Post a Comment