码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Wildcard Matching

时间:2015-11-12 01:14:10      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

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).

Example
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:

通配符匹配,很像Distinct Subsequences的思维方式。像这样给俩字串,然后看true or false的,基本DP可以用。既然给了俩字传,那就先不考虑优化问题,先开个二维空间记录结果。

状态:f(i , j) 表示S前i个跟T前j个可以不可以匹配。

方程:情况1. T(j) == ? || T(j) == S(i) (因为这两种情况都是匹配一个字符,所以放在一起)这时候 f(i, j) = f(i - 1, j - 1)。就是说T(j)必须去匹配,不然这个字母没意义了。

         情况2. T(j) == *,这时候*匹配任意字符,所以呢,f(i, j ) =f(i, j - 1) || f(i - 1, j - 1) || f(i - 2, j - 1) || f(i - 3, j - 1) ... ... || f(1, j - 1):意思就是说,S(i) 之前包括S(i)本身,只要有任意一个跟T(*)前面的一个字符匹配上,就可以。

     看起来很麻烦,但是,仔细看,这个公式可以简化:因为f(i - 1, j) = f(i - 1, j - 1) || f(i - 2, j - 1) || ... ... || f(1, j - 1), 所以上面f(i , j)  = f(i , j - 1) || f ( i - 1, j) 。

   通俗的说,就是,在当时这一dp层去考虑,我可以用*匹配 f (i - 1, j) ,也可以不用*去匹配 f (i, j - 1)。

初始化:f(0, 0 )用方程推不出,所以要单独考虑。 f(0,0) = true 意思就是null匹配null。

代码如下:

技术分享
public class Solution {
    /**
     * @param s: A string 
     * @param p: A string includes "?" and "*"
     * @return: A boolean
     */
    // f(i, j) if p(j) = ? || p(j) == s(i) ==>f(i,j) = f(i - 1, j - 1)
    //         if p(j) = *                 ==> f(i,j) = f(i - 1, j) f(i, j - 1)
    public boolean isMatch(String s, String p) {
        if (s == null){
            return p == null;
        }
        if (p == null){
            return s == null;
        }
        boolean[][] result = new boolean[s.length() + 1][p.length() + 1];
        result[0][0] = true;
        for (int i = 1; i <= s.length(); i++){
            for (int j = 1; j <= p.length(); j++){
                if (result[0][j - 1] && p.charAt(j - 1) == ‘*‘){
                    result[0][j] = true;
                }
                if (p.charAt(j - 1) == s.charAt(i - 1) || p.charAt(j - 1) == ‘?‘){
                    result[i][j] = result[i - 1][j - 1];
                }
                if (p.charAt(j - 1) == ‘*‘){
                    result[i][j] = (result[i - 1][j] || result[i][j - 1]);
                }
            }
        }
        return result[s.length()][p.length()];
     }
}
View Code

 

[LintCode] Wildcard Matching

标签:

原文地址:http://www.cnblogs.com/tritritri/p/4957759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!